user1642513
user1642513

Reputation:

Write list of comma separate strings to csv file in Python

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

Answers (2)

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

dm03514
dm03514

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

Related Questions