繁体   English   中英

读取文件python中的上一行

[英]Read previous line in a file python

我需要获取文件中前一行的值,并在迭代文件时将其与当前行进行比较。 该文件是巨大的所以我无法读取整个或随机访问行号与linecache因为库函数仍然会将整个文件读入内存。

编辑我很抱歉我忘了提到我必须向后阅读文件。

EDIT2

我尝试过以下方法:

 f = open("filename", "r")
 for line in reversed(f.readlines()): # this doesn't work because there are too many lines to read into memory

 line = linecache.getline("filename", num_line) # this also doesn't work due to the same problem above. 

只需在迭代到下一个时保存上一个

prevLine = ""
for line in file:
    # do some work here
    prevLine = line

这将在prevLine时将前一行存储在prevLine

编辑显然OP需要向后读取此文件:

aaand经过一个小时的研究后,我多次失败,在内存限制内完成

在这里你去Lim,那家伙知道他在做什么,这是他最好的想法:

一般方法#2:读取整个文件,存储行的位置

使用这种方法,您还可以读取整个文件一次,但不是将整个文件(所有文本)存储在内存中,而是仅将二进制位置存储在每行开始的文件中。 您可以将这些位置存储在与第一种方法中存储线的数据结构类似的数据结构中。

当您想要读取X行时,您必须从文件中重新读取该行,从您为该行开头存储的位置开始。

优点:几乎与第一种方法一样容易实现缺点:可能需要一段时间才能读取大文件

@Lim,这是我写的方式(回复评论)

def do_stuff_with_two_lines(previous_line, current_line):
    print "--------------"
    print previous_line
    print current_line

my_file = open('my_file.txt', 'r')

if my_file:
    current_line = my_file.readline()

for line in my_file:

    previous_line = current_line
    current_line = line

    do_stuff_with_two_lines(previous_line, current_line)

我为这个任务写了一个简单的生成器:

def pairwise(fname):
    with open(fname) as fin:
        prev = next(fin)
        for line in fin:
            yield prev,line
            prev = line

或者,您可以使用itertoolspairwise配方:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM