Get last n lines of a file, similar to tail

前端 未结 30 2900
挽巷
挽巷 2020-11-22 03:46

I\'m writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest

30条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 04:20

    If reading the whole file is acceptable then use a deque.

    from collections import deque
    deque(f, maxlen=n)
    

    Prior to 2.6, deques didn't have a maxlen option, but it's easy enough to implement.

    import itertools
    def maxque(items, size):
        items = iter(items)
        q = deque(itertools.islice(items, size))
        for item in items:
            del q[0]
            q.append(item)
        return q
    

    If it's a requirement to read the file from the end, then use a gallop (a.k.a exponential) search.

    def tail(f, n):
        assert n >= 0
        pos, lines = n+1, []
        while len(lines) <= n:
            try:
                f.seek(-pos, 2)
            except IOError:
                f.seek(0)
                break
            finally:
                lines = list(f)
            pos *= 2
        return lines[-n:]
    

提交回复
热议问题