data = [['234','123','145','134','156'],['12','67895','12345','1234']]
我想将这些数据写入csv文件,其方式是“aid,pid”是列标题。每个子列表的第一个元素是“辅助”列,其余的是“pid”。现在我想用下面的制表符编写pid。
aid,pid
234,123 145 134 156
12,67895 12345 1234
这是我的示例代码
import csv
data =[ ['234','123','145','134','156'],['12','67895','12345','1234'] ]
valid_result = open('./result/valid_result.csv','wb')
writer = csv.writer(valid_result,delimiter = ',',dialect = 'excel-tab')
header = ['aid','pid']
writer.writerow(header)
for record in data:
writer.writerow(record)
python中有什么解决方案吗?
答案 0 :(得分:1)
如果我理解正确,您需要将每个列表分成两列:
for record in data:
new_rec = [record[0], " ".join(record[1:])]
这样的事情应该做,并写下new_rec而不是记录。
答案 1 :(得分:0)
用以下代码取代你的for循环:
for record in data:
writer.writerow([record[0],'\t'.join(record[1:])])
您还必须通过valid_result.close()
关闭文件。
以下内容使用with
和open
打开并关闭该文件:
import csv
data =[ ['234','123','145','134','156'],['12','67895','12345','1234'] ]
with open('valid_result.csv','wb') as valid_result:
writer = csv.writer(valid_result,delimiter = ',',dialect = 'excel-tab')
header = ['aid','pid']
writer.writerow(header)
for record in data:
writer.writerow([record[0],'\t'.join(record[1:])])
两者都产生:
aid,pid
234,123 145 134 156
12,67895 12345 1234