CSV File Header Sequencing

Hi All

I want to re-arrange headers in csv file where i need specific filednames coming consequetively and followed with rest. I have a count of 250 columns/headers in my csv file. Do any one know how to achieve it?

Input :


In this example the headers are only 5 [A,B,C,D,E]

But i have 250 headers in my csv and in need to write 250 filed names instead of 5 field names which is not ok:

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
    for row in csv.DictReader(infile):
        # writes the reordered rows to the new file

Can you please suggest any other way , i can set up the sequence of the header when we woek on lots of data??

Can anyone please respond on the above solution???

You could skip the column when writing the file out and then append it to the end. Is that what you are looking for or do you want to arbitrarily shift columns around because i don’t know how you do the latter without having an array of all the headers.

Hi Bradhanks,

In the example i used , there are limited number of columns where we can still have a control on the order that we need to set them up when we provide columns in a array . in ex, it is fieldnames that i have read into an array in the order i want to print the results.

My question is if i have 100 plus colums how can i define the order in the way i want to add to an array like filednames. This is what i meant by sequencing the columns/headers in the way i want to print the output.

was looking is there any way to read columns/headers into array in the we want the sequence of headers/columns?