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.
So one way to tackle this problem is to use
pandas
library which can be easily install usingpip
. Basically, you can downloadcsv
file to pandas dataframe then re-order the column and save it back tocsv
file. For example, if yoursample.csv
looks like below:Here is a snippet to solve the problem.
You can use something similar to this to change the order, replacing ';' with ',' in your case. Because you said you needed to do multiple .csv files, you could use the glob module for a list of your files
You can use the csv module to read, reorder, and then and write your file.
Sample File:
Code
output
The
csv
module allows you to read csv files with their values associated to their column names. This in turn allows you to arbitrarily rearrange columns, without having to explicitly permute lists.Given the file foo.csv: