Open many files - exception handling



examples/files/average_from_files.py
import sys


def main():
    for filename in sys.argv[1:]:
        try:
            #do_some_stuff(filename)
            with open(filename) as fh:
                total = 0
                count = 0
                for line in fh:
                    number = float(line)
                    total += number
                    count += 1
                print("Average: ", total/count)
        except Exception as err:
            print(f"trouble with '{filename}': Error: {err}")

main()

examples/files/number_per_line.txt
23
1
192
17

examples/files/empty.txt


$ python average_from_files.pyt number_per_line.txt empty.txt number_per_line2.txt

Average:  58.25
trouble with empty.txt
Average:  3.5


$ python average_from_files.py numbers.txt

trouble with 'numbers.txt': Error: could not convert string to float: '23 345 12345\n'


$ python average_from_files.py more_numbers.txt

trouble with 'more_numbers.txt': Error: [Errno 2] No such file or directory: 'more_numbers.txt'