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