【发布时间】: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
这只是一件小事。感谢您的帮助。
【问题讨论】:
-
你的逻辑问题是你没有抛出 EndOfFile 错误,你只是跳过文件
-
这能回答你的问题吗? How can I check file size in Python?
-
由于 readline 不会抛出行尾错误,它只返回一个空字符串。查看以下内容以获取可能的答案How to while loop until the end of a file in Python without checking for empty line?
标签: python python-3.x exception text-files