1

I'm writing a program that uses exceptions to handle errors from multiple text files, one of which being empty. If it's empty, I need to print out a statement saying said file is empty. I have tried 'except EOFError', but that's not correct.

Code:

 def main():
    process_file("good_data.txt")
    process_file("bad_data.txt")
    process_file("empty_file.txt")
    process_file("does_not_exist.txt")


def process_file(param_str_file_name):


    #Variables
    num_rec = 0
    total = 0
    average = 0

    try:
        file_name = open(param_str_file_name, 'r')

        print("Processing file", param_str_file_name)

        one_score = file_name.readline()

        while one_score != "":
            one_score_int = int(one_score)
            num_rec = num_rec + 1

            one_score = file_name.readline()

            total += one_score_int
            average = total / num_rec

        file_name.close()

        print("\tRecord count = ", num_rec)
        print("\tTotal        = ", total)
        print("\tAverage      = ", f"{average:.2f}", "\n")

    except EOFError:
        print("\tError!", param_str_file_name,
              " is empty. Cannot calculate average\n")

    except FileNotFoundError:
        print("\tError!", param_str_file_name, " File not found\n")

    except ValueError:
        print("\tError!", param_str_file_name, "contains non-numeric data\n")


if __name__ == "__main__":
    main()

Output:

Processing file good_data.txt
    Record count =  6
    Total        =  281
    Average      =  46.83 

Processing file bad_data.txt
    Error! bad_data.txt contains non-numeric data

Processing file empty_file.txt
    Record count =  0
    Total        =  0
    Average      =  0.00 

    Error! does_not_exist.txt  File not found

It's just this one little thing to wrap up. Thanks for the help.

  • The problem with your logic is that you don't throw an EndOfFile error, you just skip the file – itprorh66 Dec 04 '20 at 22:38
  • Does this answer your question? [How can I check file size in Python?](https://stackoverflow.com/questions/2104080/how-can-i-check-file-size-in-python) – zvone Dec 04 '20 at 22:39
  • Since the readline doesn't throw end of line error it just returns a null string. Take a look at the following for a possible answer [How to while loop until the end of a file in Python without checking for empty line?](https://stackoverflow.com/questions/29022377/how-to-while-loop-until-the-end-of-a-file-in-python-without-checking-for-empty-l/29022395) – itprorh66 Dec 04 '20 at 22:42

1 Answers1

0

Here is a simple way to check if file is empty or not:

import os

size = os.path.getsize('file.txt')

if size > 0:
    print ("The file is not empty")
else:
    print ("The file is empty")
WMRamadan
  • 974
  • 1
  • 11
  • 25