Reputation: 1
Dear community, I've been trying to export a list - that I have in python - into a csv file. The code that I'm using is this one:
example = ['country1', 'country3', 'country2', 'country5', 'country4']
example2 = ['dest1', 'dest3', 'dest2', 'dest5', 'dest4']
csvFile = open('test.csv','w+', newline='')
try:
writer = csv.writer(csvFile)
writer.writerow(('number', 'number plus 2', 'number times 2'))
writer.writerows(example)
finally:
csvFile.close()
So, when I see the result, I get something like this:
number,number plus 2,number times 2
c,o,u,n,t,r,y,1
c,o,u,n,t,r,y,3
c,o,u,n,t,r,y,2
c,o,u,n,t,r,y,5
c,o,u,n,t,r,y,4
d,e,s,t,1
d,e,s,t,3
d,e,s,t,2
d,e,s,t,5
d,e,s,t,4
What I really want, is to put the "example" list down the "number" header and the "example2" list, down the "number plus" header and so on with other lists.
Then, Is it possibly to make it "row by row" and "column by column" without getting the commas? In that case, How can I do that?
Thanks a looooot! :D
Upvotes: 0
Views: 35
Reputation: 15071
This is probably what you want:
example = ['country1', 'country3', 'country2', 'country5', 'country4']
example2 = ['dest1', 'dest3', 'dest2', 'dest5', 'dest4']
example3 = list(range(5))
try:
writer = csv.writer(csvFile)
writer.writerow(('number', 'number plus 2', 'number times 2'))
for row in zip(example, example2, example3):
writer.writerow(row)
finally:
csvFile.close()
Output:
number,number plus 2,number times 2
country1,dest1,0
country3,dest3,1
country2,dest2,2
country5,dest5,3
country4,dest4,4
Upvotes: 2