Python-重新排序csv中的列 [英] Python - re-ordering columns in a csv
问题描述
我有一堆具有相同列但顺序不同的csv文件.我们正在尝试使用SQL * Plus上载它们,但我们需要具有固定列安排的列.
I have a bunch of csv files with the same columns but in different order. We are trying to upload them with SQL*Plus but we need the columns with a fixed column arrange.
示例
所需订单:A B C D E F
required order: A B C D E F
csv文件:A C D E B(有时一列不在csv中,因为它不可用)
csv file: A C D E B (sometimes a column is not in the csv because it is not available)
使用python是否可以实现?我们正在使用Access + Macros来做...但这太浪费时间了
is it achievable with python? we are using Access+Macros to do it... but it is too time consuming
PS.对不起,如果有人对我的英语技能感到沮丧.
PS. Sorry if anyone get upset for my English skills.
推荐答案
您可以使用 csv模块进行读取,重新排序,然后写入文件.
You can use the csv module to read, reorder, and then and write your file.
示例文件:
$ cat file.csv
A,B,C,D,E
a1,b1,c1,d1,e1
a2,b2,c2,d2,e2
代码
import csv
with open('file.csv', 'r') as infile, open('reordered.csv', 'a') as outfile:
# output dict needs a list for new column ordering
fieldnames = ['A', 'C', 'D', 'E', 'B']
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
# reorder the header first
writer.writeheader()
for row in csv.DictReader(infile):
# writes the reordered rows to the new file
writer.writerow(row)
输出
$ cat reordered.csv
A,C,D,E,B
a1,c1,d1,e1,b1
a2,c2,d2,e2,b2
这篇关于Python-重新排序csv中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!