在单元格中写入带分隔符的CSV文件(两点)

时间:2016-02-15 19:47:39

标签: python csv

如何写入以下.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()

3 个答案:

答案 0 :(得分:1)

您可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):

答案 1 :(得分:0)

您可以使用join

尝试:

import csv
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)
l = [':'.join(x) for x in ltarg]
for row in zip(lche,l):
    mywriter.writerow(row)
csv_out.close()

答案 2 :(得分:0)

您需要将join中的子列表(ltarg)合并到单个字符串中,同时zip使用lche列表对其内容进行ping操作。

import csv

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"
with open(data, 'wb') as csv_out:
    mywriter = csv.writer(csv_out)
    for row in zip(lche, (':'.join(v for v in lt) for lt in ltarg)):
        mywriter.writerow(row)

之后list.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