我一直在尝试解决一个基本问题(并且已经是Python 2.7,并且没有。我有一个带有列标题的csv文件,例如:
a,b,c
1,2,3
1,2,3
1,2,3
保存为test1.csv
我已经设法获取每一列并将它们传递给一个数组,因此每个列标题都在开头,然后是数据。然后,我如何将其写回具有相同顺序和结构的新csv文件?
import csv
f = open('test1.csv','rb')
reader = csv.reader(f)
headers = reader.next()
print headers
column = {}
for h in headers:
column[h] = []
for row in reader:
for h,v in zip(headers,row):
column[h].append(v)
答案 0 :(得分:2)
您可以编写(并读取)这样的数据,它使用defaultdict
而不是普通字典来简化其构造:
from collections import defaultdict
import csv
with open('test1.csv', 'rb') as f:
reader = csv.reader(f)
header = next(reader)
columns = defaultdict(list)
for row in reader:
for col,value in zip(header, row):
columns[col].append(value)
num_rows = len(columns[header[0]])
# now write data back out in same order
with open('test2.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(
tuple(columns[col][row] for col in header) for row in xrange(num_rows))