[英]Having multiple text files open
I am having trouble with a program involving three text files and processing them.我在处理涉及三个文本文件并处理它们的程序时遇到问题。 The kicker for me is getting the files to open.对我来说最重要的是让文件打开。 Am I missing something?我错过了什么吗? I have previously tried four variables but that yielded the same result.我之前尝试过四个变量,但产生了相同的结果。 I am getting "Error. {file,txt} File not found".我收到“错误。{file,txt} 找不到文件”。 so my exception is working.所以我的例外是有效的。 Any help would be appreciated.任何帮助,将不胜感激。
Here is the 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", file_name)
variable = file_name.readline()
while variable != "":
file_name_int = int(file_name)
num_rec = num_rec + 1
variable = file_name.readline()
total += file_name_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()
The files have to be in the same folder as your Python program, but other than that I don't see any problems with the code这些文件必须与您的 Python 程序位于同一文件夹中,但除此之外,我看不到代码有任何问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.