I'm tinkering with python (fairly inexperienced with the language) and file i/o, and ran across the following error:
ValueError: I/O operation on closed file.
Pretty straightforward, so I dropped in a print statement to check the state of outfile
, to see what was going on with my code:
import json
data = {'thing1' : 'foo', 'thing2' : 'bar'}
def writeToJSON():
with open('data.json', 'w') as outfile:
print outfile.closed # outputs 'False', as expected
jsonifiedData = json.dumps(data, indent=4, sort_keys=True, separators=(',', ':'), ensure_ascii=False)
outfile.write(unicode(jsonifiedData)) # trace identifies this line as the issue
writeToJSON()
Indentation seems clean, so what's going on here?
The file appears open at runtime, but the interpreter immediately complains about writing to said file after conveying as much.
Thanks!
EDIT:
Added the entire file.
Also, this is the complete output when running blurp.py
:
False
Traceback (most recent call last):
File "blurp.py", line 11, in <module>
writeToJSON()
File "blurp.py", line 9, in writeToJSON
outfile.write(unicode(jsonifiedData))
ValueError: I/O operation on closed file
outfile.write
isn't indented the way it appears to be?