Reading a Line From File Without Advancing [Pythonic Approach]
You could use wrap the file up with itertools.tee and get back two iterators, bearing in mind the caveats stated in the documentation
For example
from itertools import tee
import contextlib
from StringIO import StringIO
s = '''\
cat1
cat2
cat3
'''
with contextlib.closing(StringIO(s)) as f:
handle1, handle2 = tee(f)
print next(handle1)
print next(handle2)
cat1
cat1
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