python将字符串列表转换为CSV

时间:2019-08-29 17:49:55

标签: python csv stringio

我有一个像这样的字符串列表:

ls = [
'Header1,Header2,Header3',
'Value1,Value2,Value3',
'Value4,Value5,Value6'
]

我想将其转换为以下格式的CSV或CSV对象:

+-------+-------+-------+
|Header1|Header2|Header3|
-------------------------
|Value1 |Value2 |Value3 |
|Value4 |Value5 |Value6 |

目前,我已经尝试过:

import csv
import io

f = io.StringIO()
writer = csv.writer(f)
for i in range(len(ls)):
    writer.writerow(ls[i])

reader = csv.DictReader(f)
f.getvalue()

但是它返回如下内容:

'H,E,A,D,E,R,1,",",H,E,A,D,E,R,2,",",H,E,A,D,E,R,3,",",V,A,L,U,E,1,","

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

在将字符串添加到行之前将其拆分为可迭代的数组:

for i in range(len(ls)):
  ls[i] = ls[i].split(',')
  writer.writerow(ls[i])

Repl.it

如您所知,不这样做将逐个字符地遍历字符串。这样,数组的每个元素都将作为一个整体进行迭代。