itertools, :
from itertools import islice
from collections import deque
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
if n is None:
deque(iterator, maxlen=0)
else:
next(islice(iterator, n, n), None)
with open("in.txt") as f:
l = []
sm = 0
for i in (2, 6, 10):
i -= sm
consume(f, i-1)
l.append(next(f, ""))
sm += i
, , , i.
:
def get_lines(fle,*args):
with open(fle) as f:
l, consumed = [], 0
for i in args:
i -= consumed
consume(f, i-1)
yield next(f, "")
consumed += i
:
test.txt:
1
2
3
4
5
6
7
8
9
10
11
12
:
In [4]: list(get_lines("test.txt",2, 6, 10))
Out[4]: ['2\n', '6\n', '10\n']
In [5]: list(get_lines("stderr.txt",3, 5, 12))
Out[5]: ['3\n', '5\n', '12']
, linecache:
import linecache
linecache.getline("test.txt",10)
source
share