0

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)
user1192748
  • 945
  • 3
  • 15
  • 26
  • Can you post sample data and expected output? – Rakesh Jun 22 '18 at 16:00
  • Since you're claiming this isn't a duplicate of the other question, please [edit] your question and add _all_ the code you're using, a sample of the input file, and the (incorrect) contents of the file it produces. – martineau Jun 22 '18 at 16:25

1 Answers1

0

Look at what your DictReader is producing. You need to add delimiter=';' to the reader as well, not just the writer.

jbch
  • 591
  • 2
  • 6