I am reading through a file using a for loop like this…
f = open("somefile.txt")
for line in f:
do stuff
except for each line I read i need to take an item from the line ahead of it and put it in the current line. What is the best way to do this? Is there a way to read the next line or get some item from it without reading it?
If my understanding is correct, and you want to work on each line in turn, using some value from the next line, my suggestion would be simply to store the value you are currently reading, and work on the last value. Work in reverse – the
last_lineis your current line and line is the next one.In mathematical terms, instead of line n and line n+1, do line n-1 and line n. Same effect.
The upside to this method is it doesn’t mean loading the entire file at the beginning.