Python Forum
Handling IO Error / Reading from file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Handling IO Error / Reading from file
#11
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Excel File reading vanjoe198 1 2,006 Mar-31-2021, 11:53 AM
Last Post: snippsat
  reading from a file looseCannon101 14 4,753 Jul-18-2020, 11:29 AM
Last Post: GOTO10
  Weird problem with reading from file and performing calculations pineapple999 1 2,956 Jul-25-2019, 01:30 AM
Last Post: ichabod801
  Reading an Unconventional CSV file OzSbk 2 3,830 May-17-2019, 12:15 PM
Last Post: MvGulik
  reading text file and writing to an output file precedded by line numbers kannan 7 10,246 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  Reading of structured .mat (matlab) file sumit 2 3,369 May-24-2018, 12:12 PM
Last Post: sumit
  File Reading toxicxarrow 9 5,103 May-07-2018, 04:12 PM
Last Post: toxicxarrow
  reading all lines from a text file seadoofanatic 2 2,886 Mar-13-2018, 06:05 PM
Last Post: Narsimhachary
  Reading a text file fivestar 7 5,507 Oct-13-2017, 07:25 AM
Last Post: gruntfutuk
  Is there a specialist in error handling ? sylas 9 6,028 May-22-2017, 03:17 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020