VGu
VGu

Reputation: 396

Exporting List to CSV using Python

I am a newbie to python and here is what I am trying to achieve. I am trying to export a python created list as a csv file but it does not seem to work.

What I am expecting to see:

Name    Address    ID
A         AA       01
B         BB       05
..       ....     ....

But this is what my output looks like unfortunately:

Name    Address    ID
['A', 'AA', '01']
['B', 'BB', '05']

In other words it is clubbing all the elements of a row in the list into the first column of the output CSV file while the header elements are in their respective columns. I am hoping to populate the entries under their respective headers in the output file. I have not encountered this problem if I am reading from a csv file and writing to one.

Here's what my code looks like:

import csv
fOpen1=open('C:\master.csv')
fOpen2=open('C:\test.csv')

masterFile=csv.reader(fOpen1)
testFile=csv.reader(fOpen2)   

outputFile=open('C:\Output.csv', 'wb')
CSVWriter=csv.writer(outputFile)

masterList=list()
testList=list()
header=testFile.next()
CSVWriter.writerow(header)

for row1 in masterFile:
    if row1[0] not in masterList:
        masterList.append(row1[0])

for row2 in testFile:
    if row2[0] not in masterList:
        testList.append(row2)

CSVWriter.writerows(zip(testList))

Where do you think I am going wrong with my code? Any help and advice would be greatly appreciated.

Upvotes: 2

Views: 142

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90949

The issue is that you are doing -

CSVWriter.writerows(zip(testList))

This causes each element in the list passed to writerows() to be a tuple with a single element, which is the list (which you see outputed to the csv). Example -

>>> l = [[1,2,3,4],[4,5,6,7],[5,5,5,5]]
>>> list(zip(l))
[([1, 2, 3, 4],), ([4, 5, 6, 7],), ([5, 5, 5, 5],)]

If you directly want to write the rows in testList, you should do -

CSVWriter.writerows(testList)

If you want to transpose the testList, so that rows become columns and columns become rows, you should unpack when sending into zip() -

CSVWriter.writerows(zip(*testList))

Upvotes: 1

Related Questions