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

Python写入文件时如何校验物料名唯一性,禁止重复条目追加

物料登记重复写入问题修复方案

原有代码问题点

  • 打开文件后直接执行追加写入逻辑,未提前读取文件内已存储的物料名称做重复校验
  • 存在基础语法/变量错误:输入赋值的name/cantity变量后续被错写为nombre/cantidad、write方法调用缺少闭合括号、数量输入的提示文本和名称输入提示重复
  • 以a+模式打开文件时文件指针默认在末尾,直接读取无法获取已有内容

修复后完整代码

def wordfill(word, size):
    word = str(word)
    if len(word) % 2 == 0:
        result = ' ' * int((size - len(word))/2) + word + ' ' * int((size - len(word))/2)
    else:
        result = ' ' * int((size - len(word))/2) + word + ' ' * int((size - len(word))/2) + ' '
    return result

def registermaterial():
    print('REGISTER OF MATERIAL ')
    # 以追加读写模式打开文件
    fh = open("AQUESTO.txt","a+")
    # 将文件指针移到开头,读取所有已有物料记录
    fh.seek(0)
    existing_names = set()
    lines = fh.readlines()
    # 跳过表头行,提取所有已存物料名称,统一做去空格、转小写的标准化处理
    for line in lines[1:]:
        if not line.strip():
            continue
        mat_name = line.split('|')[0].strip().lower()
        existing_names.add(mat_name)
    
    name = input('Enter the name of the material: ').strip()
    cantity = input('Enter the quantity of the material: ').strip()
    # 重复校验
    if name.lower() in existing_names:
        print("该物料已存在于文件中")
        fh.close()
        return
    
    str_0 = wordfill(name, 30).lower()
    str_1 = wordfill(cantity, 13)
    fh.write('|{}|\t{}\n'.format(str_0, str_1))
    fh.close()

# 调用函数即可运行登记逻辑
registermaterial()

实现逻辑说明

  • 打开文件后先将指针重置到文件起始位置,读取全量历史条目
  • 跳过表头行,提取每条记录的物料名称,统一去除首尾空格、转为小写后存入集合,实现O(1)时间复杂度的快速查重
  • 获取用户输入后,对输入的物料名称做和存量数据一致的标准化处理,再和存量名称集合比对:
    • 命中重复:直接输出提示信息,关闭文件后退出流程,不执行写入
    • 无重复:按原有格式拼接内容,追加写入到文件末尾

内容的提问来源于stack exchange,提问作者María Verónica Arismendi Pérez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 08:31:01