Many time we work on files to load or process the flat files. In this post, I am showing if we receive the file but the columns are not in order then how to rearrange them in the right format. There are multiple ways to handle this but here I am using a simple python code which will reorder my columns.
Say for example my right order of my file should be as below:
empno, ename, sal
But say I receive a file with
sal, ename, empno
Now here is the simple python script which will change the file into right order :
import csv with open('file2.csv', 'r') as infile, open('file2_modified.csv', 'a') as outfile: fieldnames = ['empno','ename','sal'] writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() for row in csv.DictReader(infile): writer.writerow(row)
Save the above code as “target_file_format.py” or anyname you want.
Execute the python script , and check the result.
You can modify the code in various ways as per your need.
Thank you for reading my blog , please feel free to leave me some feedback or to suggest any future topics.