【问题标题】:Why should I close file [duplicate]我为什么要关闭文件[重复]
【发布时间】:2016-12-22 14:38:13
【问题描述】:
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)有什么区别?

【问题讨论】:

  • 为什么安全带在带安全气囊的汽车中很重要?大多数情况下,它们不是——但是当它产生影响时,你不想在没有一个的情况下坐在车里。
  • 无论如何,总是通过with访问文件。
  • 您应该始终关闭文件,因为有可能某些 IO 缓冲区可能不会被刷新(取决于语言)并且您最终可能会丢失数据。

标签: python string python-2.7


【解决方案1】:

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

【讨论】:

  • 更重要的是,一些 IO 缓冲区可能不会被刷新(取决于语言),您最终可能会丢失数据。
  • 现在更清楚了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 2010-09-24
相关资源
最近更新 更多