Just save the previous one when you go to the next
prevLine = "" for line in file: # do some work here prevLine = line
This will save the previous line to prevLine during the loop.
edit , obviously, OP should read this file back:
aaand after an hour of research, I tried several times to execute it within the limits of memory
Here you go to Lim, this guy knows what he is doing, here is his best idea:
General Approach # 2: Read the entire file, keep the line position
With this approach, you also read the entire file once, but instead of saving the entire file (all text) in memory, you only save the binary positions inside the file where each line began. You can store these positions in a similar data structure by storing rows in the first approach.
You want to read line X, you need to re-read the line from the file, starting from the position that you saved to start this line.
Pros: It's almost as easy to implement as the first approach Cons: It may take some time to read large files
source share