Python Codio异常处理练习:文件读取多余输出问题修复
问题根因
你当前代码的问题在于逐行计算时直接打印结果,只要前序行校验通过就会立刻输出,后续行触发异常时前面的输出已经产生,不符合「全量校验通过才输出所有结果、校验失败仅输出异常」的要求。
解决方案
调整逻辑,先把所有行的计算结果暂存到列表中,全量校验无异常后再统一打印所有结果。同时建议用with语句管理文件句柄,自动处理文件关闭,避免文件打开失败时finally调用close()方法报错的潜在问题。
修改后的主代码如下:
from calculate_mark import calculate_mark try: filename = input("enter a file name") # with语句会自动关闭文件,无需手动调用close with open(filename, "r") as infile: lines = infile.read().splitlines() results = [] for line in lines: # 计算结果先存入列表,不直接打印 results.append(calculate_mark(line)) # 所有行校验无异常后统一打印全部结果 for res in results: print(res) except SyntaxError: print("Corrupt file.") except ValueError: print("Values are not correct.") except FileNotFoundError: print("The file does not exist.")
如果需要保留原有finally关闭文件的写法,要提前初始化文件句柄为空,避免打开失败时报错:
from calculate_mark import calculate_mark infile = None try: infile= open(input("enter a file name" ), "r" ) s=infile.read().splitlines() results = [] for x in s: results.append(calculate_mark(x)) for res in results: print(res) except SyntaxError: print("Corrupt file.") except ValueError: print("Values are not correct.") except FileNotFoundError: print("The file does not exist.") finally: if infile is not None: infile.close()
修改后只要任意一行触发异常,程序会直接进入对应异常分支打印错误信息,不会输出前序行的计算结果,完全符合测试要求。
内容的提问来源于stack exchange,提问作者Emilia Delizia
相关产品推荐
相关产品推荐

