![python – 文件关闭错误,[AttributeError:’int’对象没有属性’close’]将文件写入代码减少到一行时,第1张 python – 文件关闭错误,[AttributeError:’int’对象没有属性’close’]将文件写入代码减少到一行时,第1张](/aiimages/python+%E2%80%93+%E6%96%87%E4%BB%B6%E5%85%B3%E9%97%AD%E9%94%99%E8%AF%AF%2C%5BAttributeError%EF%BC%9A%E2%80%99int%E2%80%99%E5%AF%B9%E8%B1%A1%E6%B2%A1%E6%9C%89%E5%B1%9E%E6%80%A7%E2%80%99close%E2%80%99%5D%E5%B0%86%E6%96%87%E4%BB%B6%E5%86%99%E5%85%A5%E4%BB%A3%E7%A0%81%E5%87%8F%E5%B0%91%E5%88%B0%E4%B8%80%E8%A1%8C%E6%97%B6.png)
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’]将文件写入代码减少到一行时所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)