Python AttributeError:NoneType对象没有属性'close' [英] Python AttributeError: NoneType object has no attribute 'close'
问题描述
这是我的代码。
from sys import argv
out_file = open(argv [2],'w')。write(open(argv [1])。read ())
out_file.close()
我得到了标题中列出的AttributeError。为什么我打开写入方法(argv [2],'w')out_file没有指定文件类型?
out_file
被分配给 write
方法,它是 None
。把这个语句分成两个部分:
$ b $ $ $ $ $ $ $ $ $ $ $ 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())
使用和
语句意味着Python会自动关闭 in_file
和 out_file
当执行离开时,
块。
I am learning python and I wrote a script that copies the content of one text file to another.
Here is my code.
from sys import argv
out_file = open(argv[2], 'w').write(open(argv[1]).read())
out_file.close()
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?
Thank you in advance
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()
And really, it'd be preferable to do this:
with open(argv[1]) as in_file, open(argv[2], 'w') as out_file:
out_file.write(in_file.read())
Using with with
statement means Python will automatically close in_file
and out_file
when execution leaves the with
block.
这篇关于Python AttributeError:NoneType对象没有属性'close'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!