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
#6
Do not add stuff to read_data function it should only do that.
If add average function that you have it would look like this.
Then make also a function for total sum.
def average(numbers):
    avg = sum(numbers) / len (numbers)
    print(f"Average = {avg:.2f}")

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 = 'nums.txt'
    numbers = read_data(file_in)
    average(numbers)
Reply


Messages In This Thread
Handling IO Error / Reading from file - by Expel - Jul-17-2019, 03:18 AM
RE: Handling IO Error / Reading from file - by snippsat - Jul-17-2019, 09:58 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Exercise on reading a chunked file of a chess game state Nit_Picker 1 549 Mar-03-2025, 05:52 AM
Last Post: Pedroski55
  Class and Object HW for cars - Help with error handling for user inputs jakeshugart 2 1,488 May-09-2024, 05:00 PM
Last Post: jakeshugart
  PayrollSystem with file handling nikadry1 1 1,306 Apr-30-2024, 03:18 PM
Last Post: deanhystad
  Excel File reading vanjoe198 1 2,576 Mar-31-2021, 11:53 AM
Last Post: snippsat
  reading from a file looseCannon101 14 7,573 Jul-18-2020, 11:29 AM
Last Post: GOTO10
  Weird problem with reading from file and performing calculations pineapple999 1 3,643 Jul-25-2019, 01:30 AM
Last Post: ichabod801
  Reading an Unconventional CSV file OzSbk 2 4,657 May-17-2019, 12:15 PM
Last Post: MvGulik
  reading text file and writing to an output file precedded by line numbers kannan 7 13,443 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  Reading of structured .mat (matlab) file sumit 2 4,200 May-24-2018, 12:12 PM
Last Post: sumit
  File Reading toxicxarrow 9 6,678 May-07-2018, 04:12 PM
Last Post: toxicxarrow

Forum Jump:

User Panel Messages

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