python头、尾和向后读取文本文件的行
如何在python中实现“head”和“tail”命令,并按文本文件的行向后读取?这是我的个人文件类;-) 用法示例:python头、尾和向后读取文本文件的行,python,file,reverse,tail,head,Python,File,Reverse,Tail,Head,如何在python中实现“head”和“tail”命令,并按文本文件的行向后读取?这是我的个人文件类;-) 用法示例: with File('file.name') as f: print f.head(5) print f.tail(5) for row in f.backward(): print row head很简单: from itertools import islice with open("file") as f: for lin
with File('file.name') as f:
print f.head(5)
print f.tail(5)
for row in f.backward():
print row
head
很简单:
from itertools import islice
with open("file") as f:
for line in islice(f, n):
print line
如果您不想将整个文件保存在内存中,那么尾部就更难了。如果输入是文件,则可以从文件末尾开始读取块。如果输入是管道,原始的tail
也可以工作,因此更通用的解决方案是读取并丢弃整个输入,最后几行除外。一个简单的方法是collections.deque
:
from collections import deque
with open("file") as f:
for line in deque(f, maxlen=n):
print line
在这两个代码段中,n
是要打印的行数。Tail:
def tail(fname, lines):
"""Read last N lines from file fname."""
f = open(fname, 'r')
BUFSIZ = 1024
f.seek(0, os.SEEK_END)
fsize = f.tell()
block = -1
data = ""
exit = False
while not exit:
step = (block * BUFSIZ)
if abs(step) >= fsize:
f.seek(0)
exit = True
else:
f.seek(step, os.SEEK_END)
data = f.read().strip()
if data.count('\n') >= lines:
break
else:
block -= 1
return data.splitlines()[-lines:]
我需要反向读取一个大的日志文件,我猜你当时并不熟悉,因为你的问题是“在python中实现tac”。使用deque和巨大的日志文件(数百MB)复制非常优雅但尾部太慢有人有python 3版本吗?我得到:name错误:未定义名称“file”
def tail(fname, lines):
"""Read last N lines from file fname."""
f = open(fname, 'r')
BUFSIZ = 1024
f.seek(0, os.SEEK_END)
fsize = f.tell()
block = -1
data = ""
exit = False
while not exit:
step = (block * BUFSIZ)
if abs(step) >= fsize:
f.seek(0)
exit = True
else:
f.seek(step, os.SEEK_END)
data = f.read().strip()
if data.count('\n') >= lines:
break
else:
block -= 1
return data.splitlines()[-lines:]