简体   繁体   English

Python打印字典到csv给出空白文件

[英]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: 我使用以下代码来表示需要打印到csv文件的更大词典:

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. 但是output.csv为空。 What am I missing? 我想念什么?

Files you open need to be closed. 您打开的文件需要关闭。 Inside a with block, that happens automatically, for example: with块内,这是自动发生的,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM