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