Python Forum

Full Version: Handling IO Error / Reading from file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Now you read the file again with no exception handling,then the whole point with this is gone Wink
To make it cleaner as mention sum could also be a function,and have to check the return Could not read file so that don't get any further.
Then will get TypeError as you have gotten.
def average(numbers):
    avg = sum(numbers) / len (numbers)
    print(f"Average = {avg:.2f}")

def total_sum(numbers):
    print(f"Total = {sum(numbers)}")

def read_data(file_in):
    try:
        with open(file_in) as nums_file:
            numbers = []
            for line in nums_file:
                numbers.append(int(line))
        return numbers
    except OSError:
        return f"Could not read file: {file_in}"

if __name__ == '__main__':
    file_in = 'nums999.txt'
    numbers = read_data(file_in)
    if 'Could not read file' in  numbers:
        print(numbers)
    else:
        average(numbers)
        total_sum(numbers)
Pages: 1 2