2012-01-24 49 views
1
from sys import argv 
from os.path import exists 

script, from_file, to_file = argv 

print "Copying from %s to %s" % (from_file, to_file) 

input = open(from_file) 
indata = input.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 continue, CTRL-C to abort." 
raw_input() 

output = open(to_file, 'w') 
output.write(indata) 

print "Alright, all done." 

output.close() 
input.close() 

爲什麼你必須在代碼中做output.close()。爲什麼input.close()也是? 如果你對此有何評論最後兩行代碼可以完美運行,沒有錯誤給出,所以我真的不明白,爲什麼你必須這樣做。LPTHW練習17,額外學分6

回答

2

儘管文件被關閉,當程序退出時(也就是當你註釋掉這些行爲什麼它仍然工作),這是很好的做法,關閉您已完成了文件。因爲如果這是一個函數,並通過一些其他的功能調用,你沒有關閉的文件,它會泄漏文件描述符和一段時間後,該程序將運行了出來。