python – 文件关闭错误,[AttributeError:’int’对象没有属性’close’]将文件写入代码减少到一行时

python – 文件关闭错误,[AttributeError:’int’对象没有属性’close’]将文件写入代码减少到一行时,第1张

概述通过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) 所以我把 通过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 sampletemp = open(to_file,'w')out_file = temp.write(indata)

现在我们可以在documentation的write()中看到:

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(),因此可能更优雅:

with open(to_file,'w') as out_file:    out_file.write(indata)

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

总结

以上是内存溢出为你收集整理的python – 文件关闭错误,[AttributeError:’int’对象没有属性’close’]将文件写入代码减少到一行时全部内容,希望文章能够帮你解决python – 文件关闭错误,[AttributeError:’int’对象没有属性’close’]将文件写入代码减少到一行时所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1194095.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存