2013-07-12 39 views
0

我想读一个非常大的文件,从一行中有一个特定的词, 什么是最好的方式来做到这一点?蟒蛇寻求读取文件到一个特定的行

可以说,它是与50K线

43511 
24622 
53213 
43534 
57656 
12121 

我要开始有43534行阅读本文件的行的文件,这将是一个大文件最有效的方法是什么?

+0

[蟒蛇:如何跳跃到一个特定的行中的一个巨大的文本文件(http://stackoverflow.com/questions/620367/python-how跳转到特定行的巨大文本文件) –

+0

该链接用于转到特定的“行号”,但这是用于具有“特定单词”的行“ –

+0

你知道行号吗?所有行都有相同数量的字符吗? –

回答

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() 

希望这有助于!

+0

我不认为你正在用'for line in f.readline():'正确地遍历文件。 'f.readline()'会返回一个字符串,所以遍历字符串会产生单个字符。你没有遍历文件中的行,你正在迭代第一行中的字符。无论如何,我们几乎在同一时间发布了几乎相同的解决方案:p –

+0

我错过了's',感谢您的领导:) –

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 
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