This question already has an answer here:
这个问题已经有了答案:
- Python Dictionary to CSV 4 answers
- Python字典到CSV 4的答案。
I have what I think should be a very easy task that I can't seem to solve.
我有我认为应该是一项很容易的任务,我似乎无法解决。
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.
如何将Python字典写入csv文件?我所要做的就是把字典的关键字写在文件的最上面一行,然后把键值写在第二行。
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.
问题是,上面的代码似乎只写了第一行的键,仅此而已。我没有把值写在第二行。
Any ideas?
什么好主意吗?
3 个解决方案
#1
121
You are using DictWriter.writerows()
which expects a list of dicts, not a dict. You want DictWriter.writerow()
to write a single row.
您使用的是DictWriter.writerows(),它期望的是一份命令列表,而不是一个命令。您需要DictWriter.writerow()来写一行。
You will also want to use DictWriter.writeheader()
if you want a header for you csv file.
如果您想要一个csv文件的头,您还需要使用DictWriter.writeheader()。
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.
您还可能需要查看带有打开文件的语句。它不仅是python和可读的,而且是为您处理关闭的,即使是在异常发生的时候。
Example with these changes made:
这些变化的例子:
import csv
my_dict = {"test": 1, "testing": 2}
with open('mycsvfile.csv', 'wb') as f: # Just use 'w' mode in 3.x
w = csv.DictWriter(f, my_dict.keys())
w.writeheader()
w.writerow(my_dict)
Which produces:
生产:
test,testing
1,2
#2
57
Your code was very close to working.
你的代码非常接近工作。
Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.
尝试使用常规的csv。而不是一个作家。后者主要用于编写字典列表。
Here's some code that writes each key/value pair on a separate row:
下面是在单独一行中编写每个键/值对的代码:
import csv
somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerows(somedict.items())
If instead you want all the keys on one row and all the values on the next, that is also easy:
如果你想要所有的键都在一行上,所有的值都在下面,这也很简单:
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerow(somedict.keys())
w.writerow(somedict.values())
Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr)
so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f)
.
专业提示:在开发这样的代码时,将作者设置为w = csv.writer(sys.stderr),这样您就可以更容易地看到正在生成的内容。当逻辑完善时,切换回w = csv.writer(f)。
#3
-11
Why use csv for this simple task?
为什么要为这个简单的任务使用csv ?
keys,values=zip(*my_dict.items())
print >>f, ", ".join(keys)
print >>f, ", ".join(values)
f.close()
I use python in two ways:
我用两种方式使用python:
1. As a proper language where I want all software engineering principles to hold in my code.
2. As a scripting language, where I want to just get something done and the code I write for this is not meant for reuse.
My answer is only useful for the 2nd purpose. And also considers the pain to remember all these modules and their individual functions :P
我的回答只对第二个目的有用。同时也考虑到所有这些模块及其各自的功能:P。
#1
121
You are using DictWriter.writerows()
which expects a list of dicts, not a dict. You want DictWriter.writerow()
to write a single row.
您使用的是DictWriter.writerows(),它期望的是一份命令列表,而不是一个命令。您需要DictWriter.writerow()来写一行。
You will also want to use DictWriter.writeheader()
if you want a header for you csv file.
如果您想要一个csv文件的头,您还需要使用DictWriter.writeheader()。
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.
您还可能需要查看带有打开文件的语句。它不仅是python和可读的,而且是为您处理关闭的,即使是在异常发生的时候。
Example with these changes made:
这些变化的例子:
import csv
my_dict = {"test": 1, "testing": 2}
with open('mycsvfile.csv', 'wb') as f: # Just use 'w' mode in 3.x
w = csv.DictWriter(f, my_dict.keys())
w.writeheader()
w.writerow(my_dict)
Which produces:
生产:
test,testing
1,2
#2
57
Your code was very close to working.
你的代码非常接近工作。
Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.
尝试使用常规的csv。而不是一个作家。后者主要用于编写字典列表。
Here's some code that writes each key/value pair on a separate row:
下面是在单独一行中编写每个键/值对的代码:
import csv
somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerows(somedict.items())
If instead you want all the keys on one row and all the values on the next, that is also easy:
如果你想要所有的键都在一行上,所有的值都在下面,这也很简单:
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerow(somedict.keys())
w.writerow(somedict.values())
Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr)
so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f)
.
专业提示:在开发这样的代码时,将作者设置为w = csv.writer(sys.stderr),这样您就可以更容易地看到正在生成的内容。当逻辑完善时,切换回w = csv.writer(f)。
#3
-11
Why use csv for this simple task?
为什么要为这个简单的任务使用csv ?
keys,values=zip(*my_dict.items())
print >>f, ", ".join(keys)
print >>f, ", ".join(values)
f.close()
I use python in two ways:
我用两种方式使用python:
1. As a proper language where I want all software engineering principles to hold in my code.
2. As a scripting language, where I want to just get something done and the code I write for this is not meant for reuse.
My answer is only useful for the 2nd purpose. And also considers the pain to remember all these modules and their individual functions :P
我的回答只对第二个目的有用。同时也考虑到所有这些模块及其各自的功能:P。