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.

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

From: stackoverflow.com/q/18952716

Back to homepage or read more recommendations: