Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read lines in a interval in Python? [duplicate]

Tags:

python

I have a txt file, there are thousands of lines there, for example:

line 1 test
line 2 test
line 3 test 
line 4 test
line 5 test
line 6 test
line 7 test
line 8 test
line 9 test

I wish to read line 1, line 4, line 7, line 10, line 13 ... but ignore line 2, 3, 5, 6, 8, 9.... How can I read these lines?

like image 304
flyingmouse Avatar asked Apr 30 '26 01:04

flyingmouse


2 Answers

you can use itertools.islice to iterate with a given step:

for line in itertools.islice(inputFile, None, None, 3):
  1. Start with the first element (start = None)
  2. End when the file does (end = None)
  3. Step by 3 lines each time, ignore the rest.

Note that I'd much prefer to specify step = 3 as a keyword but it seems islice doesn't support that. :(

This is conceptually similar to reading all the lines into memory then taking a slice of the resulting list:

all_lines = inputFile.readlines() #very memory inefficient
for line in all_lines[::3]: #step of 3, start is None and end is None.

However islice, much like everything else in itertools, is very memory efficient.

like image 168
Tadhg McDonald-Jensen Avatar answered May 01 '26 13:05

Tadhg McDonald-Jensen


Okey, I solved the problem by using for i, line in enumerate(inputFile):

like image 33
flyingmouse Avatar answered May 01 '26 15:05

flyingmouse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!