I keep getting this “writing to a closed file error” while trying to compile the following code:
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()
Don’t you want the
fout.close()outside the loop??You might want to consider using
withif you have Python 2.5 or newer:That will automatically close the file when you’re done, as well as if any exceptions occur.