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

Python modQuantity函数异常:无法写入原文件,最后两行file1为空

文件数量修改函数的写入问题排查与修复

问题描述

我编写了modQuantity函数用于修改文件中的数量信息,目前遇到以下问题:

  • 无法将内容写入原始文件
  • 即便调用write函数,代码最后两行处理的file1仍为空,其余代码运行正常

原函数代码:

def modQuantity(filepath: str,):
    model = input("Model: ")
    size = input("size")
    newquantity = input("New Quantity: ")
    file = open(filepath, 'r')
    tempfile = open(filepath+"temp", 'w')
    for line in file:
        sep = line.split()
        if sep[0] == model and sep[1] == size:
            tempfile.write(f"{sep[0]} {sep[1]} {newquantity}\n")
        else:
            tempfile.write(f"{line}")
    tempfile.close()
    file.close()
    tempfile1 = open(filepath+"temp", 'r')
    file1 = open(filepath, 'w')
    for line1 in tempfile1:
        file1.write(f"{line1}")

问题原因与修复

核心问题:文件未关闭导致缓冲区未刷新

代码最后处理file1和tempfile1时,写完后没有关闭文件。Python的文件写入有缓冲区机制,若不关闭文件,缓冲区内容不会强制刷新到磁盘,导致原始文件看起来是空的。另外手动管理文件关闭容易出现遗漏,推荐用with语句自动处理文件上下文。

修改后的代码

def modQuantity(filepath: str):
    model = input("Model: ")
    size = input("size: ")
    newquantity = input("New Quantity: ")
    
    # 写入临时文件,with语句自动关闭文件
    with open(filepath, 'r') as file, open(filepath + "temp", 'w') as tempfile:
        for line in file:
            sep = line.split()
            if sep[0] == model and sep[1] == size:
                tempfile.write(f"{sep[0]} {sep[1]} {newquantity}\n")
            else:
                tempfile.write(line)
    
    # 将临时文件内容写回原文件
    with open(filepath + "temp", 'r') as tempfile1, open(filepath, 'w') as file1:
        for line1 in tempfile1:
            file1.write(line1)

额外优化说明

  • 移除了函数参数末尾多余的逗号
  • 调整size输入提示为size: ,格式更统一
  • 写入原始行时直接使用line,无需f-string包裹,简化代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:35:15