4

我有以下dicts格式的数据:

{Color: Red, Age: 29, Date: October 2nd, Time: 4pm}

我想将这些 dicts 写入 csv,使“颜色、年龄、日期、时间”是列标题,并且字段作为行归档。这样,当我再次读取 csv 文件时,我得到的数据格式与上述相同。

解决这个问题的正确方法是什么?

4

4 回答 4

6

使用标准csv 模块,您可以使用DictWriterDictReader类来实现您想要的。

写作:

import csv

dics = [{'Color':'Red', 'Age':29, 'Date':'October 2nd', 'Time':'4pm'},
        {'Color':'Blue', 'Age':32, 'Date':'December 5th', 'Time':'6pm'},
        {'Color':'Green', 'Age':12, 'Date':'January 10th', 'Time':'2pm'}]

with open("file.csv",'wb') as f:
   # Using dictionary keys as fieldnames for the CSV file header
   writer = csv.DictWriter(f, dics[0].keys())
   writer.writeheader()
   for d in dics:
      writer.writerow(d)

阅读:

import csv

with open("file.csv", 'rb') as f:
   reader = csv.DictReader(f)
   dics = [ d for d in reader ]

>>> dics
[{'Color': 'Red', 'Date': 'October 2nd', 'Age': '29', 'Time': '4pm'},
 {'Color': 'Blue', 'Date': 'December 5th', 'Age': '32', 'Time': '6pm'},
 {'Color': 'Green', 'Date': 'January 10th', 'Age': '12', 'Time': '2pm'}]
于 2013-02-20T00:49:01.910 回答
5

使用 Pandas 很容易做到这一点:

import pandas as pd

data = [
    {"A":1.0, "B":2.0, "C":"foo"},
    {"A":100, "B":20, "C":"bar"},
    {"A":0.1, "B":0.2, "C":"xyz"},
]

df = pd.DataFrame(data)

from StringIO import StringIO
buf = StringIO()
df.to_csv(buf, index=False) # convert DataFrame to csv
print buf.getvalue()

输出是:

A,B,C
1.0,2.0,foo
100.0,20.0,bar
0.1,0.2,xyz

要加载 csv:

buf.pos = 0
print pd.read_csv(buf) 

输出是:

      A     B    C
0    1.0   2.0  foo
1  100.0  20.0  bar
2    0.1   0.2  xyz
于 2013-02-20T00:39:37.747 回答
2

如果你想使用标准库,你可以这样做:

>>> import csv
>>> dicts = [{'Color': 'Red', 'Age': '29', 'Date': 'October 2nd', 'Time': '4pm'}, {'Color': 'Yellow', 'Age': '30', 'Date': 'September 3rd', 'Time': '5pm'}]
>>> with open('test.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile, delimiter=',',
                     quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for d in dicts:
        writer.writerow([d['Color'], d['Age'], d['Date'], d['Time']])

您将在两个不同行的 csv 文件中获得以下输出::

Red,29,October 2nd,4pm
Yellow,30,September 3rd,5pm
于 2013-02-20T00:48:52.113 回答
1

您可以使用csv库并从任意数据行中提取键名。

import csv

file = open('filename', 'w')
writer = csv.writer(file)

writer.write(rows[0].keys())
for row in rows:
    writer.write(row)
于 2013-02-20T00:48:55.597 回答