Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter some lines from a textfile in python

Tags:

python

file

I am currently creating a list from an input file like this:

list = inputFile.read().splitlines()

Then after that manually iterating through and making a second list of the items/lines I care about (which are lines 2,6,10,14,18...). Is there a faster way to do this just with splitlines() so automatically, list contains only the lines I care about?

like image 261
The Nightman Avatar asked Dec 01 '25 05:12

The Nightman


1 Answers

itertools.islice(iterable, start, stop[, step]) is the tool for the job:

from itertools import islice

for line in islice(inputFile, 2, None, 4):
    print line
like image 114
alecxe Avatar answered Dec 03 '25 19:12

alecxe