在列中将数组写入csv [英] Writing arrays to a csv in columns
本文介绍了在列中将数组写入csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试解决一个基本问题(并且是python 2.7,但是没有位置.我有一个csv文件,其列标题如下:
I have been trying to solve a basic problem (and have been Python 2.7, and have got no where. I have a csv file with column headings such as:
a,b,c
1,2,3
1,2,3
1,2,3
此文件另存为test1.csv
This is saved as test1.csv
我设法将每一列都传递到数组中,所以每个列标题都在开头,然后是数据.然后,如何将其写回到具有相同顺序和结构的新csv文件中?
I have managed to take each column and pass them into an array, so each column heading is at the start, followed by the data. How would I then write this back into a new csv file with the same order and structure?
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)
推荐答案
您可以像这样编写(读取)数据,该数据使用defaultdict
而不是普通字典来简化其构造:
You could write (and read) the data like this, which uses a defaultdict
instead of a plain dictionary to simplify its construction:
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))
这篇关于在列中将数组写入csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文