Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip multiple rows in Python

so I'm trying to skip over several rows from a .txt file and then creating a CSV file using csv reader. 18 rows need to be skipped. This gets the job done but I'm pretty sure there is an easy way of skipping 18 rows instead of using next() 18 times.

import csv
import os

my_file_name = os.path.abspath('LensBank.txt')
cleaned_file = "LensBankClean.csv"
with open(my_file_name, 'r', newline='') as infile, open(cleaned_file, 'w',newline='') as outfile:
    writer = csv.writer(outfile)
    cr =  csv.reader(infile, delimiter=',')

    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    writer.writerow(next(cr))

    for line in (r[:20] for r in cr):
     writer.writerow(line)

This works for me but how would I clean up the code to a much simpler version. Thanks!

like image 224
Cesar Avatar asked Oct 20 '25 16:10

Cesar


2 Answers

Use range:

for skip in range(18):
    next(cr)
for i in range(18):
    next(cr)

Use a for loop. Or you can use itertools.dropwhile

for line in (r[:20] for i, r in itertools.dropwhile(lambda x: x[1] < 18 , enumerate(cr))):
like image 33
Patrick Haugh Avatar answered Oct 23 '25 06:10

Patrick Haugh