I am using the following code as a representation of a larger dictionary which needs to be printed to a csv file:
import csv
dict1 = {"hello": 1}
w = csv.writer(open("C:\output.csv", "w"))
for key, val in dict1.items():
w.writerow([key, val])
But the output.csv
is blank. What am I missing?
Files you open need to be closed. Inside a with
block, that happens automatically, for example:
import csv
dict1 = {"hello": "world"}
with open("C:\output.csv", "w") as fd:
w = csv.writer(fd)
for key, val in dict1.items():
w.writerow([key, val])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.