在Python中以不同的顺序写出CSV列 [英] write CSV columns out in a different order in Python

查看:677
本文介绍了在Python中以不同的顺序写出CSV列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这非常类似这个问题。但是,我有一个CSV文件,总是以相同的格式,我需要写出与列不同的顺序,将其下移到数据处理管道。如果我的csv文件包含标题和数据,像这样:

I realize this is very similar to this question. However, I have a CSV file that always comes in the same format that I need to write out with columns in a different order to move it down the data processing pipeline. If my csv file contains headers and data like this:

Date,Individual,Plate,Sample,test,QC
03312011,Indiv098,P342,A1,deep,passed
03312011,Indiv113,P352,C3,deep,passed

我如何写出一个与原始输入csv具有相同列的csv文件,但顺序如下:

How would I write out a csv file with the same columns as the original input csv but in the following order:

test,QC,Plate,Sample
deep,passed,P342,A1
deep,passed,P352,C3

我最初的想法是做这样的事情:

My initial thought was to do something like this:

f = open('test.csv')
lines = f.readlines()
for l in lines:
    h = l.split(",")
    a, b, c, d, e, f  = h
    for line in h:
        print e, f, c, d, 


推荐答案

如果输入文件或输出文件每次不会有相同的布局,这里有一个更通用的方法来获得你的reorderfunc:

If there's the slightest chance that the input file or the output file won't have the same layout each time, here's a more general way to get your "reorderfunc":

writenames = "test,QC,Plate,Sample".split(",") # example
reader = csv.reader(input_file_handle)
writer = csv.writer(output_file_handle)
# don't forget to open both files in binary mode (2.x)
# or with `newline=''` (3.x)
readnames = reader.next()
name2index = dict((name, index) for index, name in enumerate(readnames))
writeindices = [name2index[name] for name in writenames]
reorderfunc = operator.itemgetter(*writeindices)
writer.writerow(writenames)
for row in reader:
    writer.writerow(reorderfunc(row))

这篇关于在Python中以不同的顺序写出CSV列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆