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:
- Find the current position within the file using
tell
. - Perform a
read
(orwrite
) 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