【发布时间】:2017-02-10 09:34:31
【问题描述】:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
in_file = open(from_file)
indata = in_file.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
#above is the original code.
他关闭了上面的文件。但是在常见的学生问题中,有这个。
问。当我尝试缩短此脚本时,在最后关闭文件时出现错误。
A.你可能做了这样的事情,indata = open(from_file).read(),这意味着当你到达脚本末尾时你不需要再做 in_file.close()。一旦一行运行,它应该已经被 Python 关闭了。
那么,你怎么知道什么时候关闭文件,什么时候不关闭?
谢谢大家,我明白了! :)
【问题讨论】:
-
indata = in_file.read()之后可以直接关闭文件 -
无论如何你都应该使用
with构造。 -
您可以在不再需要读取文件时关闭文件,写入文件?对吗?
-
这种事情不推荐:
indata = open(from_file).read()。详情请见here。正如那个答案所说,您应该使用with打开文件,例如with open(from_file) as indata:。
标签: python