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

Python文件写入异常:删除过期行时误删多行问题排查

问题描述

需要删除keys.txt中时间戳已过期的特定行(例如ID为"54928044"的行),但执行代码后,目标行及所有上方的行被删除,最终仅保留第一行。

用户代码如下:

with open('keys.txt', 'r') as fr:
    lines = fr.readlines()
with open('keys.txt', 'w') as fr:
    for line in lines:
        if line.find(str(id)) == -1:
            fr.write(line)
            context.user_data.clear()
            return ConversationHandler.END

keys.txt内容:

('1372442', 1659568148811)
('1257406', 1659568153834)
('9910858', 1659568157498)
('1620335', 1659568165471)
('7654803', 1659568170428)
('976647', 1659568175183)
('55145660', 1660695274791)
('5496536', 1660715952400)
('15006383', 1658803605159)
('54928044', 79716354)
代码问题分析
  1. 循环提前终止:循环执行第一次迭代时,第一行不包含目标ID,写入后立刻执行return ConversationHandler.END,直接终止函数,后续所有行都未被处理,导致仅第一行被保留。
  2. 核心需求逻辑缺失:代码仅判断行中是否包含目标ID,完全没有加入时间戳过期的判断逻辑,根本没完成“删除时间戳过期的特定行”的需求。
  3. 上下文操作时机错误:context.user_data.clear()被放在循环内部,每写入一行就执行清理,且因提前return只执行了一次,不符合业务逻辑。
修正后的代码示例

以下代码实现“删除指定ID且时间戳过期的行”的需求,同时保证所有行被正确遍历处理:

import time

target_id = "54928044"
current_timestamp = int(time.time() * 1000)  # 转换为毫秒级时间戳,与文件中格式匹配

with open('keys.txt', 'r') as fr:
    lines = fr.readlines()

with open('keys.txt', 'w') as fw:
    for line in lines:
        line = line.strip()
        if not line:
            continue
        # 解析行中的ID和时间戳(仅适用于可信文本,不可信场景建议用正则解析)
        id_str, timestamp = eval(line)
        # 符合删除条件则跳过写入,否则保留该行
        if id_str == target_id and timestamp < current_timestamp:
            continue
        fw.write(line + '\n')

# 文件处理完成后统一执行上下文清理与结束操作
context.user_data.clear()
return ConversationHandler.END

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:15:30