python寻找读取文件到特定的行

时间:2013-07-12 16:27:40

标签: python file seek

我想从一个有特定单词的行中读取一个非常大的文件, 最好的方法是什么?

假设它是一个50K行的文件

43511
24622
53213
43534
57656
12121

我想从具有43534的行开始读取此文件的行,对于大文件最有效的方法是什么?

3 个答案:

答案 0 :(得分:3)

您可以使用itertools.dropwhile

t = '''43511
24622
53213
43534
57656
12121
'''


from StringIO import StringIO
import os
from itertools import dropwhile
from contextlib import closing

with closing(StringIO(t)) as f:
    for x in dropwhile(lambda x: x != '43534' + os.linesep, f):
            print x

答案 1 :(得分:1)

手动执行此操作而不会大量爆炸内存的方法可能是这样的:

f = open('file.txt','r')
found = False
for line in f
    if line == '43534':
        found = True
    if found:
        # you now reached the line in the file and
        # therefore you can begin process it here
        # in case you need the position of the buffer
        # you do: f.tell()

希望这有帮助!

答案 2 :(得分:1)

只需创建一个二进制变量来表示您是否已读入要查找的特定目标字符串。当你到达字符串时,翻转标志,触发你的脚本来读取文件的其余部分。

test = '43534'
past_test = False
with open(fname,'r') as f:
    for line in f:
        if past_test:
            # do stuff                
        elif line == test:
            past_test = True