将python Dictionary写入CSV文件,并将键作为列标题

时间:2012-10-01 20:53:26

标签: python csv dictionary

我正在尝试将字典中的元素写入文本文件,其中每个键都是一列。目前我的东西看起来像

import csv
import numpy as np



data1 = np.arange(10)
data2 = np.arange(10)*2
data3 = np.arange(10)*3

writefile = '../Desktop/data.txt'
datadict = {} 

datadict['data1'] = data1
datadict['data2'] = data2
datadict['data3'] = data3


f = open( writefile, 'w' )
fieldnames = ['data1','data2', 'data3']
data = csv.DictWriter(writefile, fieldnames, restval='', extrasaction='ignore', dialect='excel')

f.close()

但是它给了我错误“参数1必须有一个”写“方法”。我不确定这意味着什么。我也担心方言='excel',但我不确定还能放什么。 最后,我想要一个看起来像这样的文件:

enter image description here

由于

5 个答案:

答案 0 :(得分:4)

根本不需要在这里使用DictWriter:

import csv
import numpy as np

data1 = np.arange(10)
data2 = np.arange(10)*2
data3 = np.arange(10)*3

writefile = '../test.csv'
fieldnames = ['data1','data2', 'data3']
with open( writefile, 'w' ) as f:
    writer = csv.writer(f)
    writer.writerow(fieldnames)
    writer.writerows(zip(data1, data2, data3))

答案 1 :(得分:2)

您应该将类​​文件对象作为第一个参数传递给DictWriter构造函数。

datalist = [{'data1': d1, 'data2': d2, 'data3': d3} for d1, d2, d3 in zip(data1, data2, data3)]
...
f = open(writefile, 'w')
...
writer = csv.DictWriter(f, ...) 
for i in xrange(10):
    writer.writerow(datalist[i])
f.close()

更简单的类比案例:

with open(writefile, 'w') as f:
    writer = csv.writer(f)
    for row in zip(data1, data2, data3):
        writer.writerow(row)

答案 2 :(得分:1)

如果您正在进行这种数据分析,看起来您可能正在这里进行,最好的选择是进入Python的专用数据分析库pandas

这是一个做你想做的事的例子:

import pandas as pd
import numpy as np

data1 = np.arange(10)
data2 = np.arange(10)*2
data3 = np.arange(10)*3

df = pd.DataFrame(zip(data1, data2, data3), columns=['data1', 'data2', 'data3'])
df.to_csv('myfile.csv')

我说的很漂亮。此外,您现在可以使用您的数据all sorts unimaginable things

您还可以从现有字典中创建DataFrame

In [115]: a_dict = {'foo':[1,2,3], 'bar':[4,5,6], 'baz':[7,8,9]}

In [116]: pd.DataFrame(a_dict)
Out[116]: 
   bar  baz  foo
0    4    7    1
1    5    8    2
2    6    9    3

答案 3 :(得分:0)

试试这个:

import csv
import numpy as np

data1 = np.arange(10)
data2 = np.arange(10)*2
data3 = np.arange(10)*3

writefile = '../Desktop/data.txt'
datadictlist = [{'data1': data1[i], 'data2': data2[i], 'data3': data3[i]} for i in xrange(10)]

f = open( writefile, 'w' )
fieldnames = ['data1','data2', 'data3']
writer = csv.DictWriter(f, fieldnames, restval='', extrasaction='ignore', dialect='excel')
writer.writerows(datadictlist)

f.close()

答案 4 :(得分:0)

把'a +'代替'w'

f = open( writefile, 'a+' )