如何重新排序CSV的列? [英] How to reorder the columns of a CSV?
本文介绍了如何重新排序CSV的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Python重新排序CSV文件的列?这些是我需要更改的CSV文件的第一行:
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
这是所需的输出:
30269714; pgc_gral; Ramiro Alberto; Nederz
/ pre>
36185520; pgc_gral; Andrea; Espare
24884344; pgc_gral; Maria Roxana; Nietto
27461021; pgc_gral; Veronica Andrea; Lantier
24489743; pgc_gral; Diego; Moneta
第2栏现在为第1栏,第6栏为第2栏,第3栏和第4栏应保持不变,第5栏应舍弃。
解决方案尝试:
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]])
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.
解决方案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]]))
这篇关于如何重新排序CSV的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文