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
Solutions with tell()
/seek()
will not work with stdin
and other iterators. More generic implementation can be as simple as this:
class lookahead_iterator(object):
__slots__ = ["_buffer", "_iterator", "_next"]
def __init__(self, iterable):
self._buffer = []
self._iterator = iter(iterable)
self._next = self._iterator.next
def __iter__(self):
return self
def _next_peeked(self):
v = self._buffer.pop(0)
if 0 == len(self._buffer):
self._next = self._iterator.next
return v
def next(self):
return self._next()
def peek(self):
v = next(self._iterator)
self._buffer.append(v)
self._next = self._next_peeked
return v
Usage:
with open("source.txt", "r") as lines:
lines = lookahead_iterator(lines)
magic = lines.peek()
if magic.startswith("#"):
return parse_bash(lines)
if magic.startswith("/*"):
return parse_c(lines)
if magic.startswith("//"):
return parse_cpp(lines)
raise ValueError("Unrecognized file")