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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With