Cesar Cesar - 1 month ago 14
Python Question

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!

Answer

Use range:

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