私信  •  关注

Hal Canary

Hal Canary 最近创建的主题
Hal Canary 最近回复了
10 年前
回复了 Hal Canary 创建的主题 » python:从文件中读取最后的'n'行[重复]

不是第一个使用deque的例子,而是一个更简单的例子。这个是通用的:它适用于任何iterable对象,而不仅仅是文件。

#!/usr/bin/env python
import sys
import collections
def tail(iterable, N):
    deq = collections.deque()
    for thing in iterable:
        if len(deq) >= N:
            deq.popleft()
        deq.append(thing)
    for thing in deq:
        yield thing
if __name__ == '__main__':
    for line in tail(sys.stdin,10):
        sys.stdout.write(line)