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

如何获取文件追加前后行数并读取新增行?代码优化求助

问题解决与代码优化

错误原因

你的代码里用os.system("cat line_count.txt")获取历史行数是核心错误——os.system()返回的是命令的退出状态码(执行成功时为0),并非命令的输出内容,这就是prev_lc始终为0的原因。

优化后的实现逻辑

  1. 读取目标文件sample.log的所有行,同时统计当前行数;
  2. 读取line_count.txt中的历史行数:
    • 若文件不存在或内容无效,历史行数设为0;
    • 若文件正常,读取并转换为整数作为历史行数;
  3. 将当前行数写入line_count.txt覆盖旧内容;
  4. 从已读取的行中提取新增部分(从历史行数位置开始的行)。

优化代码

import os

def get_line_change_and_new_content():
    # 读取目标文件所有行并统计当前行数
    with open('sample.log', 'r') as log_f:
        all_lines = log_f.readlines()
        current_lines = len(all_lines)
    
    prev_lines = 0
    count_file = 'line_count.txt'
    
    # 读取历史行数
    if os.path.exists(count_file) and os.path.getsize(count_file) > 0:
        with open(count_file, 'r') as count_f:
            try:
                prev_lines = int(count_f.read().strip())
            except ValueError:
                # 处理文件内容非数字的情况
                prev_lines = 0
    
    # 更新行数记录
    with open(count_file, 'w') as count_f:
        count_f.write(str(current_lines))
    
    # 提取新增行
    new_content = all_lines[prev_lines:]
    
    return [prev_lines, current_lines], new_content

# 使用示例
line_counts, new_lines = get_line_change_and_new_content()
print(f"行数变化: {line_counts}")
print("新增内容:")
for line in new_lines:
    print(line.strip())

优化说明

  • 移除冗余的系统命令调用,直接用Python内置文件操作读取历史行数,高效且跨平台;
  • 增加异常处理,避免line_count.txt存在非数字内容导致程序报错;
  • 一次性读取目标文件所有行,同时完成行数统计与新增内容提取,减少IO操作次数;
  • 逻辑拆分清晰,代码结构更易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:30:17