简体   繁体   中英

Writing a python Dictionary to a CSV file with keys as column headers

I'm trying to write the elements in my dictionary into a text file where each key would be a column. Currently have I something that looks like

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

but it gives me the error "argument 1 must have a "write" method". I'm not sure what that means. I'm also worried about the dialect = 'excel', but I'm not sure what else to put. In the end I'd like a file that has something looking like:

在此输入图像描述

Thanks

No need to use DictWriter here at all:

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

You should pass the file-like object as the first argument to the DictWriter constructor.

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

More simple analogic case:

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

If you're doing the kind of data analysis it looks like you might be doing here, the best bet might be to get into pandas , Python's dedicated data analysis library.

Here's an example which does what you want:

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

Pretty neat I'd say. Additionally, you can now do all sorts of unimaginable things with your data.

You can also make a DataFrame from an existing dictionary:

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

Try this:

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

把'a +'代替'w'

f = open( writefile, 'a+' )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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