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
As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python file objects support seek and tell methods for jumping around within a file. So, the process is very simple:
tell.read (or write) operation of some kind.seek back to the previous file pointer.This allows you to do nice things like read a chunk of data from the file, analyze it, and then potentially overwrite it with different data. A simple wrapper for the functionality might look like:
def peek_line(f):
pos = f.tell()
line = f.readline()
f.seek(pos)
return line
print peek_line(f) # cat1
print peek_line(f) # cat1
You could implement the same thing for other read methods just as easily. For instance, implementing the same thing for file.read:
def peek(f, length=1):
pos = f.tell()
data = f.read(length) # Might try/except this line, and finally: f.seek(pos)
f.seek(pos)
return data
print peek(f, 4) # cat1
print peek(f, 4) # cat1