我为什么要关闭文件

时间:2016-12-22 14:38:14

标签: python string python-2.7

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_filein_file)之间有什么区别?

1 个答案:

答案 0 :(得分:5)

通过不关闭文件,您可能会浪费系统资源。此外,在代码执行后想要访问文件的其他进程可能无法执行此操作,因为代码仍会打开它。