转到文件中的特定行

Rek*_*koc 3 python python-2.7

在此期间for line in f:,我的代码保存了包含特定数据的行.不幸的是,我必须阅读整个文件,而不是最重要的数据.在第二次,我必须检查整个文件(在5000-8000行之间),直到我多次获得正确的行(对于每个数据).

所以,我的问题是,可以打开一个文件并转到一个特定的行,阅读它并再次执行.我看到了不同的答案,但是我无法保存所有文件,str因为我的设备上没有那么多内存......这就是我想直接在文件中搜索的原因.

Net*_*ave 5

使用迭代器和生成器,文件xreadlines(python 2)进行延迟评估,以便在使用之前文件没有加载到内存中:

def drop_and_get(skiping, it):
    for _ in xrange(skiping):
        next(it)
    return next(it)
f = xrange(10000)#lets say your file is this generator
drop_and_get(500, iter(f))
500
Run Code Online (Sandbox Code Playgroud)

所以你可以执行以下操作:

with open(yourfile, "r") as f:
    your_line = drop_and_get(5000, f.xreadlines())
    print your_line
Run Code Online (Sandbox Code Playgroud)

实际上甚至可以跳过,xreadlines因为文件对象本身就是一个迭代器

with open(yourfile, "r") as f:
    your_line = drop_and_get(5000, f)
    print your_line
Run Code Online (Sandbox Code Playgroud)

  • 是的,我的坏,你是对的.否则`next`不能被调用.但是使用文件句柄它可以工作.很公平.您可以在示例中添加python 3兼容代码. (2认同)