Python AttributeError:NoneType 对象没有属性“关闭" [英] Python AttributeError: NoneType object has no attribute 'close'

查看:62
本文介绍了Python AttributeError:NoneType 对象没有属性“关闭"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 python,我编写了一个脚本,将一个文本文件的内容复制到另一个文本文件.

I am learning python and I wrote a script that copies the content of one text file to another.

这是我的代码.

from sys import argv
out_file = open(argv[2], 'w').write(open(argv[1]).read())
out_file.close()

我在标题中列出了 AttributeError.为什么我在 open(argv[2], 'w') 上调用 write 方法,out_file 没有分配文件类型?

I get the AttributeError listed on the title. Why is it that wen I call the write method on open(argv[2], 'w') the out_file is not assigned a File type?

提前致谢

推荐答案

out_file 被赋值给 write 方法的返回值,即 None.将语句一分为二:

out_file is being assigned to the return value of the write method, which is None. Break the statement into two:

out_file = open(argv[2], 'w')
out_file.write(open(argv[1]).read())
out_file.close()

实际上,最好这样做:

with open(argv[1]) as in_file, open(argv[2], 'w') as out_file:
    out_file.write(in_file.read())

使用 with with 语句意味着 Python 将在执行离开 with 块时自动关闭 in_fileout_file.

Using with with statement means Python will automatically close in_file and out_file when execution leaves the with block.

这篇关于Python AttributeError:NoneType 对象没有属性“关闭"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆