Writing a python Dictionary to a CSV file with keys as column headers
Question: 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:

![enter image description here](http://i.stack.imgur.com/QJILB.png)

Thanks


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

