文件关闭错误,[AttributeError:'int'对象没有属性'close']时将文件写入代码减少到单个lin

2024-05-13 05:17:05 发布

您现在位置:Python中文网/ 问答频道 /正文

阅读Zed Shaw的练习17[关于将一个文件复制到另一个文件]中,他减少了这两行代码

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

合二为一:

^{pr2}$

还有一段他写的代码

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()是如何工作的?在


Tags: 文件to代码infromclosereadopen
3条回答

write方法返回文件中写入的字符数,这是一个整数而不是文件对象,因此没有close方法。在

In [6]: a = open('test', 'w')          
In [7]: t = a.write('ssss')
In [8]: t
Out[8]: 4

另外,只有当您不想与文件进行任何进一步的交互时,才建议直接在open()上调用I/O方法。另外,处理file对象最合适的方法是使用with语句,该语句在块的末尾自动关闭文件,不需要手动调用close()。在

^{pr2}$

两者不是等价的。如果您写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) writes the contents of string to the file, returning the number of characters written.

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

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

^{pr2}$

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

以下通常是更好的阅读和写作方法:

with open("myfile.txt", "w") as f:
    # do something with f

不需要用此代码关闭f。在

对于代码val = open(to_file, 'w').write(indata),“val”将是write函数的返回值,而不是open函数的返回值。在

相关问题 更多 >