关闭文件时触发AttributeError:《笨办法学Python》ex17问题
问题分析与解决方法
错误原因
你触发的AttributeError本质是:
from_file是从命令行参数获取的文件名字符串(str类型),不是通过open()创建的文件对象。只有文件对象才有close()方法,字符串没有这个属性,所以调用from_file.close()会报错。- 另外,你用
indata = open(from_file).read()这种写法时,Python会在读取完成后自动关闭文件:open()创建的临时文件对象在read()执行后没有被变量引用,会被Python垃圾回收机制自动清理,清理时会关闭文件,根本不需要手动关闭。
直接修正方案
删掉报错的from_file.close()即可,同时注意原代码缺少argv的导入,需要补上:
from os.path import exists from sys import argv # 补充导入argv,否则会触发NameError script, from_file, to_file = argv print(f"Copying from {from_file} to {to_file}") # 简化后的读取方式,文件会自动关闭 indata = open(from_file).read() print(f"The input file is {len(indata)} bytes long") print(f"Does the output file exist? {exists(to_file)}") print("Ready, hit RETURN to continue, CTRL-C to abort.") input() out_file = open(to_file, 'w') out_file.write(indata) print("Alright, all done.") out_file.close() # 移除错误的from_file.close()
更规范的写法(推荐)
使用Python的with上下文管理器,它会自动处理文件的打开和关闭,避免手动管理可能出现的遗漏或错误:
from os.path import exists from sys import argv script, from_file, to_file = argv print(f"Copying from {from_file} to {to_file}") # with语句自动关闭文件 with open(from_file) as in_file: indata = in_file.read() print(f"The input file is {len(indata)} bytes long") print(f"Does the output file exist? {exists(to_file)}") print("Ready, hit RETURN to continue, CTRL-C to abort.") input() # 写入也用with语句,无需手动close with open(to_file, 'w') as out_file: out_file.write(indata) print("Alright, all done.")
内容的提问来源于stack exchange,提问作者Dasani Drink
相关产品推荐
相关产品推荐

