6

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?

4

2 回答 2

13

您可以创建列表列表(行)并使用writerows将它们全部写入。或将它们全部单独编写。重要的部分是一行是一个 python 列表,而不是一个逗号分隔值的字符串。

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()
于 2012-09-02T23:50:57.620 回答
2

以下适用于字符串。

   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()
于 2017-05-11T16:38:58.523 回答