Reading a Line From File Without Advancing [Pythonic Approach]

后端 未结 5 2056
日久生厌
日久生厌 2021-01-01 10:24

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         


        
5条回答
  •  长发绾君心
    2021-01-01 11:05

    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")
    

提交回复
热议问题