如何将 Python 字典写入 csv 文件? [英] How do I write a Python dictionary to a csv file?

查看:49
本文介绍了如何将 Python 字典写入 csv 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我认为应该很容易但我似乎无法解决的任务.

I have what I think should be a very easy task that I can't seem to solve.

如何将 Python 字典写入 csv 文件?我想要的只是将字典键写入文件的第一行,将键值写入第二行.

How do I write a Python dictionary to a csv file? All I want is to write the dictionary keys to the top row of the file and the key values to the second line.

我最接近的是以下内容(我从别人的帖子中得到的):

The closest that I've come is the following (that I got from somebody else's post):

f = open('mycsvfile.csv','wb')
w = csv.DictWriter(f,my_dict.keys())
w.writerows(my_dict)
f.close()

问题是,上面的代码似乎只是将键写入第一行,仅此而已.我没有将值写入第二行.

The problem is, the above code seems to only be writing the keys to the first line and that's it. I'm not getting the values written to the second line.

有什么想法吗?

推荐答案

您正在使用 DictWriter.writerows() 它需要一个 dict 列表,而不是一个 dict.您希望 DictWriter.writerow() 写入一行.

You are using DictWriter.writerows() which expects a list of dicts, not a dict. You want DictWriter.writerow() to write a single row.

如果您想要 csv 文件的标题,您还需要使用 DictWriter.writeheader().

You will also want to use DictWriter.writeheader() if you want a header for you csv file.

您可能还想查看with声明用于打开文件.它不仅更具 Python 风格和可读性,而且可以为您处理关闭操作,即使发生异常也是如此.

You also might want to check out the with statement for opening files. It's not only more pythonic and readable but handles closing for you, even when exceptions occur.

进行这些更改的示例:

import csv

my_dict = {"test": 1, "testing": 2}

with open('mycsvfile.csv', 'w') as f:  # You will need 'wb' mode in Python 2.x
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

产生:

test,testing
1,2

这篇关于如何将 Python 字典写入 csv 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆