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

如何修改文本文件中的整数值?修复Python更新库存txt数值错乱问题

问题描述

我编写的库存更新代码仅在Inventory.txt内所有存储值均为个位数时可以正常完成更新,一旦库存文本文件中包含两位及以上位数的数值,文件更新后就会出现内容错乱,该如何修复?
相关参考截图:
库存文本文件示例
商品编码文件对应代码示例

原有实现代码如下:

import os
# 用于存储数据的空列表
codes=[]
inventories=[]
# 以读模式打开商品编码文本文件
code= open("Code.txt","r")
for line in code:
    line1=line.rstrip()
    line1=int(line1)
    codes.append(line1)

# 以读写模式打开库存文本文件
Inventory=open("Inventory.txt","r+")
for line in Inventory:
    line1=line.rstrip()
    line1=int(line1)
    inventories.append(line1)

def inventory_update(a,b):
    while True:
        global cs1
        cs1= int(input("Enter the item's code:"))
        if cs1 in a:
            for x in range(0,len(a)):
                if cs1==a[x]:
                    print("Stock:",b[x])
                    while True:
                        ar=input("Add/Remove/Done(a/r/d):")
                        ar=ar.lower()
                        if ar=="a":
                            add=int(input("How many to add?:"))
                            b[x] += add
                            print("Stock:",b[x])
                        elif ar=="r":
                            remove=int(input("How many to remove?:"))
                            b[x] -= remove
                            print("Stock:",b[x])
                        elif ar=="d":
                            print(cs1,":",b[x])
                            Inventory.seek(x+x,os.SEEK_SET)  
                            Inventory.write(str(b[x]))
                            Inventory.seek(0,os.SEEK_SET)
                            Inventory.close()
                            break                          
            break
        else:
            print("Invalid code")
inventory_update(codes,inventories)
故障原因

核心问题出在文件写入的定位逻辑上:

  • 代码里用Inventory.seek(x+x,os.SEEK_SET)定位写入位置,默认每一行库存值固定占2字节(1位数字+1个换行符),所以第x行的起始偏移量按2*x计算。这个逻辑只有所有库存值都是个位数时才成立,一旦数值变成两位、三位,每行实际占用的字节数是「数字长度+1(换行符)」,固定偏移计算完全错误,写入时会直接覆盖其他行的内容,造成文件错乱。
  • 即使偏移量计算正确,原地写入单值的逻辑也有问题:如果修改后的数值长度和原值不一样(比如从9变成10,长度从1变2),写入时同样会侵占后面行的存储空间,破坏文件结构。
  • 代码直接手动管理文件句柄,没有异常保护,中途报错会导致文件无法正常关闭,也可能造成内容损坏。
修复方法

文本文件不要做单值原地偏移修改,最稳妥的方式是把所有库存数据读取到内存完成修改后,全量重写整个文件,完全不需要手动计算seek偏移:

# 读取商品编码
codes = []
with open("Code.txt", "r", encoding="utf-8") as f:
    for line in f:
        stripped_line = line.strip()
        if stripped_line:
            codes.append(int(stripped_line))

# 读取库存数据
inventories = []
with open("Inventory.txt", "r", encoding="utf-8") as f:
    for line in f:
        stripped_line = line.strip()
        if stripped_line:
            inventories.append(int(stripped_line))

def inventory_update(code_list, stock_list):
    while True:
        input_code = int(input("Enter the item's code:"))
        if input_code not in code_list:
            print("Invalid code")
            continue
        # 直接取对应商品的索引,不需要冗余全量循环
        idx = code_list.index(input_code)
        print("Stock:", stock_list[idx])
        while True:
            op = input("Add/Remove/Done(a/r/d):").lower()
            if op == "a":
                add_num = int(input("How many to add?:"))
                stock_list[idx] += add_num
                print("Stock:", stock_list[idx])
            elif op == "r":
                remove_num = int(input("How many to remove?:"))
                stock_list[idx] -= remove_num
                print("Stock:", stock_list[idx])
            elif op == "d":
                print(input_code, ":", stock_list[idx])
                # 修改完成后全量重写库存文件
                with open("Inventory.txt", "w", encoding="utf-8") as f:
                    for stock in stock_list:
                        f.write(f"{stock}\n")
                break
        break

inventory_update(codes, inventories)

这个实现不管库存值是几位数,都不会出现内容错乱的问题,同时用with上下文管理文件句柄,就算中途报错也不会损坏文件。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 04:45:38