【发布时间】: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_file 和 in_file)有什么区别?
【问题讨论】:
-
为什么安全带在带安全气囊的汽车中很重要?大多数情况下,它们不是——但是当它产生影响时,你不想在没有一个的情况下坐在车里。
-
无论如何,总是通过
with访问文件。 -
您应该始终关闭文件,因为有可能某些 IO 缓冲区可能不会被刷新(取决于语言)并且您最终可能会丢失数据。
标签: python string python-2.7