Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to reverse lines in a csv file python

I want to know the best way to reverse the lines of a big csv file (+50000 lines) in python 2.7 and rewrite it, avoiding the first line.

input:
A;B;C
1;2;3
4;5;6

output
A;B;C
4;5;6
1;2;3

I need to know how to do it in a efficient way in python 2.7.

Thank you guys,

menchopez

like image 443
menchopez Avatar asked Oct 28 '25 09:10

menchopez


1 Answers

read the csv file using csv module and open the output also using csv module. Now you're working with lists as rows.

Use next to write the title line as-is. Now that the first line is consumed, convert the rest of the data into a list to read it fully and apply writerows on the reversed list:

import csv

with open("in.csv") as fr, open("out.csv","wb") as fw:
    cr = csv.reader(fr,delimiter=";")
    cw = csv.writer(fw,delimiter=";")
    cw.writerow(next(cr))  # write title as-is
    cw.writerows(reversed(list(cr)))

writerows is the fastest way of doing it, because it involves no python loops.

Python 3 users have to open the output file using open("out.csv","w",newline="") instead.

like image 165
Jean-François Fabre Avatar answered Oct 29 '25 23:10

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!