You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在文件最后一行无'Completed'时,获取'alienbutt'最后出现行及后续内容?

解决方案

需求说明

若文件最后一行不包含字符串Completed,需查找字符串alienbutt的最后出现位置,并获取该行及以下所有内容。

完整实现代码

from pathlib import Path
import os

logfile = Path(r'\\server\carlsagan\cosmos.log')

with open(logfile, 'rb') as f:
    # 获取文件最后一行
    try:
        f.seek(-2, os.SEEK_END)
        while f.read(1) != b'\n':
            f.seek(-2, os.SEEK_CUR)
    except OSError:
        f.seek(0)
    last_line = f.readline().decode()

if 'Completed' in last_line:
    print('you found it')
else:
    # 逆向查找'alienbutt'最后出现位置
    with open(logfile, 'rb') as f:
        block_size = 1024
        target_bytes = b'alienbutt'
        target_len = len(target_bytes)
        found_pos = -1

        f.seek(0, os.SEEK_END)
        file_size = f.tell()
        pos = max(0, file_size - block_size)
        f.seek(pos)

        # 分块逆向扫描文件
        while pos > 0 or f.tell() < file_size:
            current_block = f.read()
            idx = current_block.rfind(target_bytes)
            if idx != -1:
                found_pos = pos + idx
                break
            pos = max(0, pos - block_size)
            f.seek(pos)

        if found_pos != -1:
            # 定位到目标字符串所在行的开头
            f.seek(found_pos)
            while f.tell() > 0:
                f.seek(-1, os.SEEK_CUR)
                char = f.read(1)
                if char == b'\n':
                    break
                f.seek(-1, os.SEEK_CUR)
            # 读取该行及后续所有内容
            content = f.read().decode()
            print("获取到的内容:")
            print(content)
        else:
            print("文件中未找到'alienbutt'")

关键逻辑说明

  • 高效逆向扫描:采用分块逆向读取的方式,避免一次性加载大文件,适合处理大容量日志文件
  • 行首定位:找到alienbutt的位置后,向前回溯至最近的换行符,确保获取完整的目标行及后续内容
  • 边界处理:兼容文件过小、目标字符串位于文件开头等特殊情况

内容的提问来源于stack exchange,提问作者LifeMy333

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 11:35:41