最有效的方法来搜索python中文件的最后一行 [英] Most efficient way to search the last x lines of a file in python
本文介绍了最有效的方法来搜索python中文件的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
s =foo
last_bit = fileObj.readlines()[ - 10:]
在last_bit中的行:
如果行== s:
打印FOUND
解决方案
#尾
从__future__导入with_statement
find_str =FIREFOX#字符串查找
fname =g:/autoIt/ActiveWin.log_2#文件检查
with open(fname, r)as f:
f.seek(0,2)#Seek @ EOF
fsize = f.tell()#获取大小
f.seek(max(fsize-1024 ,0),0)#设置pos @ last n chars
lines = f.readlines()#读取结束
lines = lines [-10:]#获取最后10行
#如果任何行完全是find_str +\\\
打印find_str +\\\
在行
#如果你是为li搜索一个子串
ne行:
如果find_str在行中:
print True
break
I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:
s = "foo"
last_bit = fileObj.readlines()[-10:]
for line in last_bit:
if line == s:
print "FOUND"
解决方案
# Tail
from __future__ import with_statement
find_str = "FIREFOX" # String to find
fname = "g:/autoIt/ActiveWin.log_2" # File to check
with open(fname, "r") as f:
f.seek (0, 2) # Seek @ EOF
fsize = f.tell() # Get Size
f.seek (max (fsize-1024, 0), 0) # Set pos @ last n chars
lines = f.readlines() # Read to end
lines = lines[-10:] # Get last 10 lines
# This returns True if any line is exactly find_str + "\n"
print find_str + "\n" in lines
# If you're searching for a substring
for line in lines:
if find_str in line:
print True
break
这篇关于最有效的方法来搜索python中文件的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文