from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying fro %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)
print "Ready, hit RETURN to countinue, CRL-C to abort."
raw_input("?")
out_file = open(to_file, 'w')
out_file.write(indata)
print "Alright, all done."
out_file.close()
in_file.close()
是否有必要撰写out_file.close()
和in_file.close()
?
如果我不写最后两行,仍然有效。关闭两者(out_file
和in_file
)之间有什么区别?
答案 0 :(得分:5)
通过不关闭文件,您可能会浪费系统资源。此外,在代码执行后想要访问文件的其他进程可能无法执行此操作,因为代码仍会打开它。