Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip first couple of lines while reading lines in Python file

I want to skip the first 17 lines while reading a text file.

Let's say the file looks like:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 good stuff 

I just want the good stuff. What I'm doing is a lot more complicated, but this is the part I'm having trouble with.

like image 215
O.rka Avatar asked Mar 06 '12 05:03

O.rka


People also ask

How do you skip a reading line in Python?

There are many ways in which you can skip a line in python. Some methods are: if, continue, break, pass, readlines(), and slicing.


2 Answers

Use a slice, like below:

with open('yourfile.txt') as f:     lines_after_17 = f.readlines()[17:] 

If the file is too big to load in memory:

with open('yourfile.txt') as f:     for _ in range(17):         next(f)     for line in f:         # do stuff 
like image 137
wim Avatar answered Sep 22 '22 00:09

wim


Use itertools.islice, starting at index 17. It will automatically skip the 17 first lines.

import itertools with open('file.txt') as f:     for line in itertools.islice(f, 17, None):  # start=17, stop=None         # process lines 
like image 30
Ismail Badawi Avatar answered Sep 21 '22 00:09

Ismail Badawi