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

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

变成一个:
indata = open(from_file).read()

他还写了一段代码
out_file = open(to_file, 'w')
out_file.write(indata)

所以我把它简化成一行:
out_file = open(to_file, 'w').write(indata)

这似乎工作正常,但当我关闭out_file时,会出现如下错误:
Traceback (most recent call last):
  File "filesCopy.py", line 27, in <module>
    out_file.close()
AttributeError: 'int' object has no attribute 'close'

我无法理解发生了什么,以及close()在这里是如何工作的?

最佳答案

两者并不等同如果您写的是out_file = open(to_file, 'w').write(indata),那么您已经隐式地写了:

# equivalent to second code sample
temp = open(to_file, 'w')
out_file = temp.write(indata)

现在我们可以在write()documentation中看到:
f.write(string)将字符串的内容写入文件,并返回写入的字符数。
所以它返回一个整数。所以在第二个示例中out_file不是一个文件处理程序,而是一个整数在代码的后面,您可以使用out_file关闭out_file.close()文件处理程序但是由于out_file不再是文件处理程序,因此对此调用close是没有意义的。
然而,通过使用上下文,您不再需要自己执行.close(),因此更优雅的可能是:
with open(to_file, 'w') as out_file:
    out_file.write(indata)

书本身的减少是允许的(至少在语义上,最好使用上下文管理器),因为作者可能永远不会显式地关闭文件句柄。

09-10 06:53
查看更多