您可以使用itertools中的consume函数,它是跳过多行的最快方法之一。
这里有详细介绍。
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)
current_file.seek
。但在大多数情况下,您不知道,需要扫描文件以查找行的结束位置(寻找\n
字符)。正如ZdaR所指出的那样,无论如何最好读取完整个文件(这相当于扫描它)。 - user707650\n
结尾的10GB(文本?)文件,并且需要在任意位置访问行,那么你可能需要重新考虑你的存储模型。 - user707650