查看第8行和最后一行(标有注释),就最佳做法而言,是否需要关闭“from_file”?我尝试在最后一行(from_file.close())关闭,但这会产生错误:
AttributeError: 'str' object has no attribute 'close'
将代码更改为indata.close()会产生相同的错误。 (并且没有任何意义,因为indata是变量,而不是文件。)
在将内容分配给indata变量后,from_file是否自动关闭?或者如果没有,我该如何手动关闭它?
谢谢!
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)
# the next line is the issue
indata = open(from_file).read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
output = open(to_file, 'w')
output.write(indata)
print "All right, all done."
output.close()
#this line is the issue
from_file.close()