如何将以下内容写入.csv文件:

1171837, 1974:3655:1862:279:1936
1172, 238:1833:228:234:1821:225:211:245:1941:315:2035:222:3371:231:224:216:1942


代替这个:

1171837, ['1974', '3655', '1862', '279', '1936']
1172, ['238', '1833', '228', '234', '1821', '225', '211', '245', '1941', '315', '2035', '222', '3371', '231', '224', '216', '1942']


这些是我的清单:

lche=['1171837', '1172']
ltarg=[['1974', '3655', '1862', '279', '1936'],
       ['238', '1833', '228', '234', '1821', '225', '211', '245', '1941',
        '315', '2035', '222', '3371', '231', '224', '216', '1942']]


这就是我的方法。我不知道如何使用其他定界符。

data="list.csv"
csv_out = open(data, 'wb')
mywriter = csv.writer(csv_out)
for row in zip(lche,ltarg):
    mywriter.writerow(row)
csv_out.close()

最佳答案

您可以join ltarg的元素和冒号:

>>> ltarg2 = list()
>>> for elem in ltarg:
...     ltarg2.append(':'.join(elem))
...
>>> ltarg2
['1974:3655:1862:279:1936', '238:1833:228:234:1821:225:211:245:1941:315:2035:222:3371:231:224:216:1942']


然后继续处理新列表:

for row in zip(lche,ltarg2):

关于python - 在单元格中写入带分隔符的CSV文件(两点),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35417822/

10-16 06:58