【问题标题】:Check if a text file is empty in Python检查 Python 中的文本文件是否为空
【发布时间】:2021-03-16 23:24:48
【问题描述】:

我正在编写一个程序,它使用异常来处理来自多个文本文件的错误,其中一个是空的。如果它是空的,我需要打印出一个声明说文件是空的。我试过“除了 EOFError”,但这是不正确的。

代码:

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

输出:

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

这只是一件小事。感谢您的帮助。

【问题讨论】:

标签: python python-3.x exception text-files


【解决方案1】:

这是检查文件是否为空的简单方法:

import os

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

if size > 0:
    print ("The file is not empty")
else:
    print ("The file is empty")

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多