Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - re-ordering columns in a csv

Tags:

python

csv

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.

Example

required order: A B C D E F

csv file: A C D E B (sometimes a column is not in the csv because it is not available)

is it achievable with python? we are using Access+Macros to do it... but it is too time consuming

PS. Sorry if anyone get upset for my English skills.

like image 894
JJ1603 Avatar asked Oct 07 '15 20:10

JJ1603


People also ask

How do you change the order of columns in Python?

You can change the order of columns in the pandas dataframe using the df. reindex() method.

How do I reorder columns in pandas?

Reorder Columns using Pandas . Another way to reorder columns is to use the Pandas . reindex() method. This allows you to pass in the columns= parameter to pass in the order of columns that you want to use.


1 Answers

You can use the csv module to read, reorder, and then and write your file.

Sample File:

$ cat file.csv A,B,C,D,E a1,b1,c1,d1,e1 a2,b2,c2,d2,e2 

Code

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) 

output

$ cat reordered.csv A,C,D,E,B a1,c1,d1,e1,b1 a2,c2,d2,e2,b2 
like image 83
Josh J Avatar answered Sep 19 '22 10:09

Josh J