Last active
December 14, 2015 02:19
-
-
Save mdjhny/5013161 to your computer and use it in GitHub Desktop.
用python实现的类似tail的程序
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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