-1

How can I re-order the columns of a CSV file using Python? These are the first rows of a CSV file I need to change:

03;30269714;Ramiro Alberto;Nederz;active;pgc_gral
03;36185520;Andrea;Espare;active;pgc_gral
03;24884344;Maria Roxana;Nietto;active;pgc_gral
03;27461021;Veronica Andrea;Lantier;active;pgc_gral
71;24489743;Diego;Moneta;active;pgc_gral

This is the desired output:

30269714;pgc_gral; Ramiro Alberto;Nederz
36185520;pgc_gral; Andrea;Espare
24884344;pgc_gral;Maria Roxana;Nietto
27461021;pgc_gral;Veronica Andrea;Lantier
24489743;pgc_gral;Diego;Moneta

Column 2 is now column 1, column 6 is column 2, columns 3 and 4 should stay the same and column 5 should be discarded.

08Dc91wk
  • 4,254
  • 8
  • 34
  • 67
MV_81
  • 111
  • 1
  • 9
  • 3
    Did you try to solve it already? post some code that we can review and help guide you – Sina Khelil Jul 27 '15 at 20:29
  • Take a look at http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html, csv isn't sophisticated enough to do translations – FirebladeDan Jul 27 '15 at 20:30

1 Answers1

1

Try this:

import csv

with open('yourfile.csv') as f:
    reader = csv.reader(f, delimiter=';')
    for row in reader:
        print(";".join([row[1], row[5], row[2], row[3]]))
Ewan
  • 14,592
  • 6
  • 48
  • 62
  • Hello.. I have a similar need to write to a csv file as well. So I used "," as a separator : with open('abc.csv', 'r', newline='',encoding='utf-8') as f1, open('xyz.csv', 'w', newline='',encoding='utf-8') as _finalf: reader = csv.reader(finalf, delimiter=',') writer = csv.writer(_finalf,delimiter=',') for row in reader: row=",".join([row[0], row[1], row[2], row[5], row[3],row[4]]) print(row) But each and every characters in each field is showing separately: N A M E , A G E, H E I G H T J O H N , 1 2 3, S M A L L Can you please suggest? – rantish Jul 10 '23 at 19:01
  • The link https://stackoverflow.com/questions/32996230/change-order-of-columns-in-csv-python worked for me to reorder csv columns. – rantish Jul 12 '23 at 07:33