2011年2月16日 星期三

python file.close()的重要性

今天在批次處理字串的時候,有個奇怪的錯誤產生,就是在檔案結尾之處的文字會莫名其妙的消失掉。這個程式執行起來需要半個小時左右,而這個錯誤大概是在程式的中段產生。程式運行的邏輯如下:


【1】不同的文字檔案(.txt)
【2】combine成一個文字檔案 
【3】把文字檔案做千字切成個別的檔案
【4】對每個檔案做gram的切


在這個過程中的【2】出現了錯誤,造成之後【3】的檔案在總字數上不統一。在程式的中段才出現這個錯誤的確是會讓人頭大。找老師debug了半個小時才找到了錯誤。


這是我在開檔案寫入的問題,需要做的修正如下:


fin = codecs.open('input.txt','r','utf-8')
......
fout = codecs.open('output.txt','w','utf-8')
fout.write(strings)
fout.close()


我忘記了把檔案.close()起來,會讓檔案寫進buffer裡面沒有再次寫出來,結果就造成結尾的地方有漏掉的字串。


晚上自己再去python's official website 去檢索相關的資訊。




file.close()



Close the file. A closed file cannot be read or written any more. Any operation which requires that the file be open will raise a ValueError after the file has been closed. Calling close() more than once is allowed.
As of Python 2.5, you can avoid having to call this method explicitly if you use the with statement. For example, the following code will automatically closef when the with block is exited:
from __future__ import with_statement # This isn't required in Python 2.6

with open("hello.txt") as f:
    for line in f:
        print line
In older versions of Python, you would have needed to do this to get the same effect:
f = open("hello.txt")
try:
    for line in f:
        print line
finally:
    f.close()



這個with的寫法我還不熟悉,需要多做練習。幸好這次debug有老師的幫助,不然我應該會做到死@@。這個故事也說明了觀念的重要性,我在開關檔案和os module的地方還不夠熟悉。

沒有留言:

張貼留言