GobSmack GobSmack - 1 month ago 16
Python Question

Valueerror : I/O operation on closed file

import csv

with open('v.csv', 'w') as csvfile:
cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

for w, c in p.iteritems():
cwriter.writerow(w + c)


Here, p is a dictionary, w and c both are strings.

When I try to write in the file it reports error :
Valueerror : I/O operation on closed file.

Help me, I'm really new to python. I'm working with Python 2.7.3
Thank you in advance.

Answer

Indent correctly; for statement should be inside with block:

import csv    

with open('v.csv', 'w') as csvfile:
    cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

    for w, c in p.iteritems():
        cwriter.writerow(w + c)

Outside the with block, the file is closed.

>>> with open('/tmp/1', 'w') as f:
...     print f.closed
... 
False
>>> print f.closed
True