Skip to content

Instantly share code, notes, and snippets.

@mdjhny
Last active December 14, 2015 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdjhny/5013161 to your computer and use it in GitHub Desktop.
Save mdjhny/5013161 to your computer and use it in GitHub Desktop.
用python实现的类似tail的程序
from mmap import mmap
def tail(fn, count=10):
with open(fn,'r+') as f:
data = mmap(f.fileno(), 0)
pos = len(data)
for _ in range(count):
pos = data.rfind('\n', 0, pos)
if pos == -1:
pos = 0
break
return data[pos:].split('\n')
#另外一种思路
import os
def tail(fn, n=1):
'''返回文件fn中最后n行'''
N, data = 1024, ''
f = open(fn, 'rb')
fsize = os.path.getsize(fn)
f.seek(0, 2)
for i in xrange(fsize-N, -N, -N):
last_loc = f.tell()
f.seek(max(i, 0))
data = f.read(last_loc-f.tell()) + data
if data.count('\n') > n:
break
f.seek(max(i, 0))
lines = data.splitlines()[-n:]
for line in lines:
print line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment