Zanam
Zanam

Reputation: 4807

python printing dictionary to csv gives blank file

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?

Upvotes: 0

Views: 63

Answers (1)

user2127434
user2127434

Reputation:

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])

Upvotes: 1

Related Questions