ValueError: I / O operation in a 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 are strings.

When I try to write to a file, it reports an error:

 ValueError : I/O operation on closed file. 

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

+68
python io file-io csv
Sep 23 '13 at 6:08 on
source share
3 answers

Indentation is correct; for should be inside the 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 
+103
Sep 23 '13 at 6:09
source share

The same error can occur when mixing : tabs + spaces.

 with open('/foo', 'w') as f: (spaces OR tab) print f <-- success (spaces AND tab) print f <-- fail 
+2
Mar 26 '18 at 21:43
source share

printing should be intended inside the "c" cycle:

 @app.route("/sheet", methods=["GET"]) def get_sheet(): with open ("survey.csv", "r") as new_file: csv_reader = csv.reader(new_file) for line in new_file: first= line[0] last= line[1] return render_template("sheet.html", first=first, last=last) 
0
Jan 27 '19 at 17:11
source share



All Articles