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

Python文件操作:如何避免重复写入并跳过已追加内容?

解决方案:实现仅写入一次目标行并跳过已追加内容

问题分析

你的代码当前存在两个核心问题:

  1. 每次运行会读取文件中所有内容(包括之前追加的结果行),结果行无法转为整数会触发报错;
  2. 未记录已处理的请求,导致重复运行时会重复写入相同的处理结果。

下面提供两种可行的实现方案:


方案一:单文件分隔符区分请求与结果

通过在文件中加入固定分隔符,将原始请求行和处理结果行分开,读取时仅处理分隔符前的请求,同时解析结果行标记已处理的请求,避免重复写入。

修正后的代码:

kitty = 500
# 定义分隔符,用于区分请求和结果区域
SEPARATOR = "--- REQUESTS END ---"

# 1. 读取文件,分离原始请求和已有处理结果
requests = []
existing_results = []
try:
    with open("loan_requests.txt", "r") as file:
        lines = file.readlines()
        separator_found = False
        for line in lines:
            stripped_line = line.strip()
            # 找到分隔符后,后续行均为结果行
            if stripped_line == SEPARATOR:
                separator_found = True
                continue
            if not separator_found:
                # 仅处理数字格式的请求行
                try:
                    req = int(stripped_line)
                    requests.append(req)
                except ValueError:
                    continue
            else:
                existing_results.append(line)
except FileNotFoundError:
    # 如果文件不存在,初始化请求列表(可根据需求调整)
    requests = [100, 200, 300, 0]

# 2. 从已有结果中提取已处理的请求金额
processed_requests = []
for line in existing_results:
    if "Request of" in line or "Outstanding Request:" in line:
        # 解析结果行中的请求金额
        for part in line.split():
            if part.isdigit():
                processed_requests.append(int(part))
                break

# 3. 处理未被处理过的请求
new_results = []
for req in requests:
    if req == 0:  # 原逻辑中的请求结束标记
        break
    if req in processed_requests:
        continue  # 跳过已处理的请求

    # 处理请求的核心逻辑(修正原代码的计算错误)
    if req <= kitty and kitty > 0:
        kitty -= req
        print(f"{req} - Paid!")
        new_results.append(f"Request of {req} paid in full.\n")
    elif req > kitty and kitty > 0:
        paid_amount = kitty
        kitty -= req
        print(f"{req} Request cannot be processed in full (Insufficient funds available). Amount paid: {paid_amount}")
        new_results.append(f"Request of {req} could not be paid in full. Partial payment of {paid_amount} made.\n")
    elif req > kitty and kitty <= 0:
        print(f"Request of {req} is UNPAID!")
        new_results.append(f"Outstanding Request:{req}\n")

# 4. 重新写入文件:请求行 + 分隔符 + 已有结果 + 新结果
with open("loan_requests.txt", "w") as file:
    # 写入原始请求行
    for req in requests:
        file.write(f"{req}\n")
    # 写入分隔符
    file.write(f"{SEPARATOR}\n")
    # 写入已有结果
    file.writelines(existing_results)
    # 写入新结果
    file.writelines(new_results)

方案说明

  • 用SEPARATOR标记请求区域的结束,读取时仅处理该标记之前的数字行;
  • 解析已有结果行提取已处理的请求金额,确保同一请求不会被重复处理;
  • 修正了原代码中loan = int(item) + kitty的计算错误,改为正确的paid_amount = kitty;
  • 处理文件不存在的情况,初始化默认请求列表(可根据实际需求调整)。

方案二:分离请求与结果到不同文件

将原始请求和处理结果分别存储到两个文件,逻辑更清晰,避免解析结果行的复杂度:

kitty = 500
REQUEST_FILE = "loan_requests.txt"
RESULT_FILE = "payment_results.txt"

# 1. 读取原始请求
try:
    with open(REQUEST_FILE, "r") as f:
        requests = [int(line.strip()) for line in f if line.strip().isdigit()]
except FileNotFoundError:
    requests = [100, 200, 300, 0]

# 2. 读取已有结果,提取已处理的请求
processed_requests = []
try:
    with open(RESULT_FILE, "r") as f:
        for line in f:
            if "Request of" in line or "Outstanding Request:" in line:
                for part in line.split():
                    if part.isdigit():
                        processed_requests.append(int(part))
                        break
except FileNotFoundError:
    pass

# 3. 处理未处理的请求
new_results = []
for req in requests:
    if req == 0:
        break
    if req in processed_requests:
        continue

    if req <= kitty and kitty > 0:
        kitty -= req
        print(f"{req} - Paid!")
        new_results.append(f"Request of {req} paid in full.\n")
    elif req > kitty and kitty > 0:
        paid_amount = kitty
        kitty -= req
        print(f"{req} Request cannot be processed in full (Insufficient funds available). Amount paid: {paid_amount}")
        new_results.append(f"Request of {req} could not be paid in full. Partial payment of {paid_amount} made.\n")
    elif req > kitty and kitty <= 0:
        print(f"Request of {req} is UNPAID!")
        new_results.append(f"Outstanding Request:{req}\n")

# 4. 将新结果追加到结果文件
with open(RESULT_FILE, "a") as f:
    f.writelines(new_results)

方案说明

  • 原始请求仅存储在loan_requests.txt中,不会被修改;
  • 处理结果追加到payment_results.txt,每次运行仅读取该文件标记已处理的请求;
  • 逻辑更简洁,避免了重新写入整个请求文件的操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:10:37