python写入文件

python写入文件,python,Python,在尝试编译以下代码时,我一直遇到“写入闭合文件错误”: 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( su

在尝试编译以下代码时,我一直遇到“写入闭合文件错误”:

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()

您不希望
fout.close()
在循环之外吗

如果您有Python 2.5或更新版本,您可能需要考虑使用:

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

完成后,以及出现任何异常时,都会自动关闭文件。

每次通过循环时,您都要关闭
fout
。取消缩进fout.close(),它应该能按预期工作。

fout.close()
似乎在for循环中

取消该行的缩进,以实现预期的行为。

您的
fout.close()
发生在
for
循环中。它将在第一项之后关闭,而不是在操作结束时关闭


为了清晰/稳健性,建议在处理文件时使用
with
操作符

为什么要关闭循环中的文件?这可能只会写入一条记录,然后文件就会关闭。这是你的本意吗?或者你的缩进是错的?因为他是字形,另一个+1;)请注意,在Python2.5中,您必须使用
from\uuuuuuuuuuuuuuuuuuuuuuuuuu语句导入。