python写入文件

daw*_*ife 2 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( 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()
Run Code Online (Sandbox Code Playgroud)

Gly*_*yph 6

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