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 :
File.csv
A,B,C,D,E
a1,b1,c1,d1,e1
a2,b2,c2,d2,e2
Output:
File.csv
A,C,D,E,B
a1,c1,d1,e1,b1
a2,c2,d2,e2,b2
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
writer.writeheader()
for row in csv.DictReader(infile):
# writes the reordered rows to the new file
writer.writerow(row)
Can you please suggest any other way , i can set up the sequence of the header when we woek on lots of data??