简体   繁体   中英

Check if a text file is empty in Python

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.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM