Is there a way to skip a specific line number when reading a file in Python?

I use the csv library to parse the file. I need to skip 6 lines and go straight to the 7th line and analyze the rest. I can run reader.next() 6 times, but it looks weird:

 reader = csv.reader(csvfile) reader.next() reader.next() reader.next() reader.next() reader.next() reader.next() for row in reader: print row 

So, I am wondering if there is a way to skip 6 lines in another way?

+5
source share
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 iterability, then the following positional arguments work just like your typical start-stop-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, negative indexing is not 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, therefore, for example, for each line starting from the first (i.e. line with even numbers):

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

Or each line starting with the second line (for example, an odd-numbered line):

 for row in islice(reader, 1, None, 2): print row 
+10
source

You can do:

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

Or you can wrap this 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 it in a generator:

 for row in (e for i, e in enumerate(reader) if i not in (1,13,666)): print row 
0
source

Source: https://habr.com/ru/post/1270936/


All Articles