Basically, I want to achieve exactly the same task that was solved in the approved answer here.
However, this solution does not work for me in case the input CSV file uses semicolons as delimiters. I tried to change the code to be
writer = csv.DictWriter(outfile, fieldnames=fieldnames, delimiter = ';')
but it does not do the trick and just results in a CSV with the new order, good header, but empty data (i.e., only the delimiters are written).
I am sorry to create a duplicate but given the age of the original post, I doubt that anyone would notice my question / comment over there.
I am using the following code:
#!/usr/bin/env python3
import sys, os, csv
def reorder():
with open('in.csv', 'r') as infile, open('out.csv', 'a') as outfile:
fieldnames = ['A', 'C', 'D', 'E', 'B']
writer = csv.DictWriter(outfile, fieldnames=fieldnames, delimiter = ';')
writer.writeheader()
for row in csv.DictReader(infile):
writer.writerow(row)
def main():
reorder()
# standard boilerplate to call the main() function to begin the program
if __name__ == '__main__':
main()
Given in.csv
with the following content does not produce a good result:
A;B;C;D;E
a1;b1;c1;d1;e1
a2;b2;c2;d2;e2
Replacing the semicolon with commas produces a good result.
Update:
I changed the respective piece of code as follows, which works:
with open('in.csv', 'r') as infile, open('out.csv', 'w') as outfile:
reader = csv.DictReader(infile, fieldnames = ['A', 'B', 'C', 'D', 'E'], delimiter=';')
fieldnames = ['A', 'C', 'D', 'E', 'B']
writer = csv.DictWriter(outfile, fieldnames=fieldnames, delimiter=';')
writer.writeheader()
for row in reader:
writer.writerow(row)