从文件关闭时属性错误?-通过艰苦的方式学习python ex17



这项工作的子目标是缩小第9&10组成一行。我试图打开from文件并阅读它,但由于某种原因,在最后一行它给了我这个:

"第23行,infrom_file.close((AttributeError:"str"对象没有属性"close">

我不特别知道str是什么,但我主要只是想关闭文件。很抱歉写得不好,我还是新来的,谢谢你抽出时间。

from os.path import exists
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}")
#I am attempting to shorten the code here
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()
# This line is drawing the attribute error
from_file.close()

from_file指的是文件的路径。这是python中的str类型。要关闭文件,需要存储open()调用的输出。在这里,您永远不会将open()调用的输出存储在第8行。相反,您可以立即对其调用.read(),并将其值存储到变量indata中。您可以将第8行替换为以下行:

opened_from_file = open(from_file)
indata = opened_from_file.read()

然后,关闭您的文件,将第23行替换为:

opened_from_file.close()

此外,使用上下文管理器而不是手动打开/关闭文件被认为是最佳做法,因为它们总是会关闭您的文件(目前,如果程序中出现错误,您的文件仍在内存中(。请在此处阅读为什么应该使用上下文管理器进行文件i/o:https://book.pythontips.com/en/latest/context_managers.html

最新更新