JavaScript
x
8
1
import csv
2
3
with open('v.csv', 'w') as csvfile:
4
cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
5
6
for w, c in p.items():
7
cwriter.writerow(w + c)
8
Here, p
is a dictionary, w
and c
both are strings.
When I try to write to the file it reports the error:
JavaScript
1
2
1
ValueError: I/O operation on closed file.
2
Advertisement
Answer
Indent correctly; your for
statement should be inside the with
block:
JavaScript
1
8
1
import csv
2
3
with open('v.csv', 'w') as csvfile:
4
cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
5
6
for w, c in p.items():
7
cwriter.writerow(w + c)
8
Outside the with
block, the file is closed.
JavaScript
1
7
1
>>> with open('/tmp/1', 'w') as f:
2
print(f.closed)
3
4
False
5
>>> print(f.closed)
6
True
7