Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
142 views
Welcome To Ask or Share your Answers For Others

1 Answer

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]]))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...