python直接跳转到最后一行,最有效的方法来搜索python中文件的最后一行

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值