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!
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))):
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