将文件写入代码减少到单行时,文件关闭错误,[AttributeError: 'int' object has no attribute 'close']

f__*_*ety 5 python file-io python-3.x

浏览 Zed Shaw 的书《练习 17》[关于将一个文件复制到另一个文件],他在其中减少了这两行代码

in_file = open(from_file)
indata = in_file.read()
Run Code Online (Sandbox Code Playgroud)

合为一:

indata = open(from_file).read()
Run Code Online (Sandbox Code Playgroud)

还有一段他写的代码

out_file = open(to_file, 'w')
out_file.write(indata)
Run Code Online (Sandbox Code Playgroud)

所以我将其简化为与上面相同的一行:

out_file = open(to_file, 'w').write(indata)
Run Code Online (Sandbox Code Playgroud)

这似乎工作正常,但当我关闭时out_file出现错误:

Traceback (most recent call last):
  File "filesCopy.py", line 27, in <module>
    out_file.close()
AttributeError: 'int' object has no attribute 'close'
Run Code Online (Sandbox Code Playgroud)

我无法了解正在发生的事情以及close()这里的工作情况如何?

Wil*_*sem 4

两者并不等同。如果你写out_file = open(to_file, 'w').write(indata),你就隐式地写了:

# equivalent to second code sample
temp = open(to_file, 'w')
out_file = temp.write(indata)
Run Code Online (Sandbox Code Playgroud)

现在我们可以在文档中看到write()

f.write(string)将 string 的内容写入文件,返回写入的字符数

所以它返回一个整数。因此,在第二个示例中out_file不是文件处理程序,而是整数。在代码的进一步部分中,您的目标是使用. 但由于不再是文件处理程序,因此调用 close 是没有意义的。out_fileout_file.close()out_file

然而,通过使用上下文,您不再需要.close()自己执行,因此更优雅的方式可能是:

with open(to_file, 'w') as out_file:
    out_file.write(indata)
Run Code Online (Sandbox Code Playgroud)

本书本身的减少是允许的(至少在语义上,最好使用上下文管理器),因为作者可能从未明确关闭文件句柄。