What\'s a pythonic approach for reading a line from a file but not advancing where you are in the file?
For example, if you have a file of
cat1
cat2
Manually doing it is not that hard:
f = open('file.txt')
line = f.readline()
print line
>>> cat1
# the calculation is: - (length of string + 1 because of the \n)
# the second parameter is needed to move from the actual position of the buffer
f.seek((len(line)+1)*-1, 1)
line = f.readline()
print line
>>> cat1
You can wrap this in a method like this:
def lookahead_line(file):
line = file.readline()
count = len(line) + 1
file.seek(-count, 1)
return file, line
And use it like this:
f = open('file.txt')
f, line = lookahead_line(f)
print line
Hope this helps!