2

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() 
1
  • 1
    Why are you closing the file inside the loop? That would probably only write one record and then the file would be closed. Is that what you intended? Or is your indentation wrong? Commented Dec 6, 2010 at 18:23

4 Answers 4

5

You're closing fout each time through the loop. Un-indent fout.close() and it should work as expected.

Sign up to request clarification or add additional context in comments.

1 Comment

And because he is Glyph, another +1 ;)
3

Don't you want the fout.close() outside the loop??

You might want to consider using with if you have Python 2.5 or newer:

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

That will automatically close the file when you're done, as well as if any exceptions occur.

1 Comment

Note that in Python 2.5 you have to use from __future__ import with_statement.
1

fout.close() seems to be inside the for loop.

Un-indent that line, for the intended behavior.

Comments

1

Your fout.close() occurs inside the for loop. It will be closed after the first item, not at the end of the operation.

For clarity/robustness, it is recommended to use the with operator when dealing with files.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.