为什么要关闭文件

Inf*_*ite -2 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()
Run Code Online (Sandbox Code Playgroud)

有必要写out_file.close()in_file.close()吗?

如果我不写最后两行,仍然可以使用。同时关闭(out_file,和in_file)有什么区别?

小智 5

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

  • 更重要的是,某些IO缓冲区可能不会被刷新(取决于语言),并且最终可能会丢失数据。 (2认同)