Reputation:
If I have a list of strings as follows:
data = ['a,x', 'b,y', 'c,z']
f = open('data.csv', 'wb')
w = csv.writer(f, delimiter = ',')
w.writerow(data)
f.close()
The problem is that they are saved in 3 cells on a single line like this: (" " is one Excel cell)
"a,x" "b,y" "c,z"
What I really want is the following:
"a" "x"
"b" "y"
"c" "z"
so that they are in separate cells and separate lines. Does anyone know how to do this correctly?
Upvotes: 6
Views: 30620
Reputation: 21
The below works for Strings.
import csv
data = ["Apparels,Clothings,Materials,Bazaar,Saree,Salwars"]
f = open('data.csv', 'w')
w = csv.writer(f, delimiter = ',')
w.writerows([x.split(',') for x in data])
f.close()
Upvotes: 2
Reputation: 55962
You can create a list of lists(row) and write them all using writerows. or write them all individually. The important part is that a row is a python list, not a string with comma seperated values.
data = ['a,x', 'b,y', 'c,z']
f = open('data.csv', 'wb')
w = csv.writer(f, delimiter = ',')
w.writerows([x.split(',') for x in data])
f.close()
Upvotes: 13