7

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?

0

2 Answers 2

13

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()
Sign up to request clarification or add additional context in comments.

Comments

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.