Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to skip to a specific line number while reading a file in Python? [duplicate]

Tags:

python

csv

I'm using the csv library to parse a file. I need to skip 6 rows and go straight to the 7th row and parse the rest. I'm able to run reader.next() 6 times, but it looks odd:

reader = csv.reader(csvfile)

reader.next()
reader.next()
reader.next()
reader.next()
reader.next()
reader.next()

for row in reader:
    print row

So I'm wondering if there's a way to skip 6 rows another way?

like image 345
simplycoding Avatar asked Aug 16 '17 18:08

simplycoding


2 Answers

Yes. Use itertools.islice:

from itertools import islice
reader = csv.reader(csvfile)

for row in islice(reader, 7, None):
    print row

This islice takes an iterable, then the following positional arguments work a lot like your typical list-slicing start-stop-step:

>>> x = list(range(14))
>>> x[7:None]
[7, 8, 9, 10, 11, 12, 13]
>>> x[7:]
[7, 8, 9, 10, 11, 12, 13]
>>>
>>> list(islice(x, 7, None))
[7, 8, 9, 10, 11, 12, 13]

However, no negative indexing allowed.

>>> list(islice(x, -1, None))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Indices for islice() must be None or an integer: 0 <= x <= maxint.
>>>

However, it is still very flexible, so, for example, taking every-other row starting at the first (i.e. even-numbered rows):

for row in islice(reader, None, None, 2):
    print row

Or every-other row starting at the second row (i.e. odd-numbered rows):

for row in islice(reader, 1, None, 2):
   print row
like image 82
juanpa.arrivillaga Avatar answered Sep 26 '22 00:09

juanpa.arrivillaga


You could do:

for i, row in enumerate(reader):
    if i<7: continue 
    print row

Or you can wrap that in a generator:

for row in (e for i, e in enumerate(reader) if i>=7):
    print row   

If you want to skip some specific lines:

for i, row in enumerate(reader):
    if i in (1,13,666): continue # skip unlucky lines... 
    print row

Or, wrapping that in a generator:

for row in (e for i, e in enumerate(reader) if i not in (1,13,666)):
    print row   
like image 44
dawg Avatar answered Sep 24 '22 00:09

dawg