加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 文件关闭错误,[AttributeError:’int’对象没有属性

发布时间:2020-12-20 12:05:18 所属栏目:Python 来源:网络整理
导读:通过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 sample
temp = 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)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读