Python AttributeError:NoneType 对象没有属性“close”

Bis*_*its 5 python file attributeerror

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

这是我的代码。

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

我得到标题上列出的 AttributeError 。为什么当我在 open(argv[2], 'w') 上调用 write 方法时,out_file 没有分配 File 类型?

先感谢您

dan*_*ano 5

out_file被分配给该write方法的返回值,即None。将语句分成两部分:

out_file = open(argv[2], 'w')
out_file.write(open(argv[1]).read())
out_file.close()
Run Code Online (Sandbox Code Playgroud)

实际上,最好这样做:

with open(argv[1]) as in_file, open(argv[2], 'w') as out_file:
    out_file.write(in_file.read())
Run Code Online (Sandbox Code Playgroud)

使用with语句意味着当执行离开块时withPython将自动in_file关闭。out_filewith