2010-12-06 161 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运算符。