2010-12-06 156 views
2

我不斷收到這種「寫一個封閉的文件錯誤」,同時試圖編譯下面的代碼:蟒蛇寫入文件

fout = open('markov_output.txt', 'w') 

for i in range(MAXGEN) : 
      # get our hands on the list 
    key = (w1,w2) 
    sufList = table[key] 
      # choose a suffix from the list 
    suf = random.choice(sufList) 

    if suf == NONWORD :  # caught our "end story" marker. Get out 
      if len(line) > 0 : 
        fout.write(line) 
      break 
    if len(line) + len(suf) > MAX_LINE_LEN : 
      fout.write(line) 
      line = "" 
    line = line + " " + suf 

    w1, w2 = w2, suf 
    fout.close() 
+1

你爲什麼要關閉**循環內的文件**?這可能只會寫入一條記錄,然後該文件將被關閉。這是你的意圖嗎?還是你的縮進錯了? – 2010-12-06 18:23:39

回答

3

你不想要的外循環fout.close()

你可能想,如果你有Python的2.5或更新版本考慮使用with

with open('markov_output.txt', 'w') as fout: 
    # Your code to write to the file here 

當你做,它會自動關閉文件,以及如果有例外發生。

+1

請注意,在Python 2.5中,您必須使用`from __future__ import with_statement`。 – 2010-12-06 18:30:37

+0

@Brent:是的,沒錯。謝謝你注意到這一點。 – 2010-12-06 18:31:10

6

您正在通過循環每次關閉fout。取消縮進fout.close()它應該按預期工作。

1

fout.close()似乎是for循環內。

取消縮進該行,用於預期的行爲。

1

您的fout.close()發生在for循環內部。它將在第一個項目後關閉,而不是在操作結束時關閉。

爲了清晰/健壯,建議在處理文件時使用with運算符。