我有一堆列表,我已压缩:
zipped = zip(list1, list2, list3)
我有一个csv文件(已经有标题)看起来像这样:
Col_1 Col_2 Col_3
data data data
现在我想将我的压缩列表添加为已存在文件的列,以便它看起来像这样(列表名称为标题):
Col_1 Col_2 Col_3 list1 list2 list3
data data data data data data
我现在有了这个代码:
with open('existing.csv', 'rb') as infile, open('out_file.csv', 'wb') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
writer.writerow(["list1", "list2", "list3"])
for i, row in enumerate(reader):
row.extend(zipped[i])
writer.writerow(row)
但是,不幸的是,这会覆盖现有的列名。
答案 0 :(得分:2)
您需要保留现有标题,即读者对象的第一行:
with open('existing.csv', 'rb') as infile, open('out_file.csv', 'wb') as outfile:
reader = csv.reader(infile)
header = next(reader) # get header
writer = csv.writer(outfile)
# create list with old header and new
writer.writerow(header+["list1", "list2", "list3"])
您还可以使用itertools.izip
压缩for循环中调用next的列表来获取每个子元素:
from itertools import izip
zipped = izip(list1, list2, list3)
with open('existing.csv', 'rb') as infile, open('out_file.csv', 'wb') as outfile:
reader = csv.reader(infile)
headers = next(reader)
writer = csv.writer(outfile)
writer.writerow(headers+["list1", "list2", "list3"])
for row in reader:
row.extend(next(zipped))
writer.writerow(row)
你自己的代码实际上不会覆盖标题,它会添加你的新标题,然后直接用压缩列表中的第一个子元素压缩原始标题。