在Python中以不同的顺序写出CSV列

时间:2011-05-24 23:00:45

标签: python csv

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

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

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

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

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

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, 

4 个答案:

答案 0 :(得分:5)

reorderfunc = operator.itemgetter(4, 5, 2, 3)

 ...

newrow = reorderfunc(oldrow)
 ...

答案 1 :(得分:5)

如果输入文件或输出文件每次都没有相同布局的可能性,这里有一个更通用的方法来获取“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))

答案 2 :(得分:4)

根据您的输入src.csv

import csv

with open('x.csv','rb') as i:
    with open('y.csv','wb') as o:
        r = csv.DictReader(i)
        w = csv.DictWriter(o,'test QC Plate Sample'.split(),extrasaction='ignore')
        w.writeheader()
        for a in r:
            w.writerow(a)

输出

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

答案 3 :(得分:0)

#Use CSV library
import csv
media = {}
files=['Online.txt']
directory = "C:/directory/"
rowCnt=0

for file in files:

    file=directory+file

    with open(file, 'rb') as f:
        reader = csv.reader(f, delimiter='|') #use pipe delimiter

        for row in reader:
            rowCnt+=1
            if (rowCnt % 1000) == 0:
                print ('"%s","%s","%s","%s","%s","%s","%s","%s","%s"')% (row[1],row[4],row[14],row[17],row[18],row[24],row[25],row[28],row[30])