Python追加写入txt文件失败回退主菜单问题排查
库存管理程序写入TXT文件失败问题排查
问题现象
开发库存管理程序时,需实现用户输入商品名称、预估价格、库存数量后,将对应商品信息保存到txt文本文件的功能。当前异常表现为:程序执行打开txt文件写入内容的操作时,无实际数据写入文件,程序直接循环回退到主菜单函数,仅打印Please choose a valid action!错误提示,相关代码如下:
def user_interface_menu(): while True: try: print(""" -------------------------------------------------------------- Menu -------------------------------------------------------------- 1 - Show one item information 2 - Show all stock information 3 - Add item 4 - Update item 5 - Remove item 6 - Save and exit 7 - Exit without save""") user_action = int(input("Action - ")) if user_action not in (1, 2, 3, 4, 5, 6, 7): print("Please choose a valid action!") elif user_action == 1: one_item_information() elif user_action == 2: all_stock_information() elif user_action == 3: add_item() elif user_action == 4: update_item() elif user_action == 5: remove_item() elif user_action == 6: save_exit() elif user_action == 7: exit_no_save() except: print("Please choose a valid action!") def add_item(): try: stock_name = input(""" Please state the name of the product. - """) stock_name = str(stock_name) price_estimate = input(""" Please state the estimated price of the product. - """) price_estimate = float(price_estimate) stock_quantity = input(""" Please state the quantity of the product. - """) stock_quantity = int(stock_quantity) print("") print("New item Added! - ", end="") print(stock_name, price_estimate, stock_quantity) with open("store_stock.txt", "a") as f: user_addition = input("") f.write(stock_name, price_estimate, stock_quantity) f.write("\n") except: print("incorrect")
故障原因
- 存在无意义的阻塞输入语句:
add_item()函数打开文件后,第一行是无任何提示的user_addition = input(""),程序运行到这里会暂停等待用户输入,但控制台没有任何提示,用户很容易误以为回到了菜单选择步骤,直接输入菜单序号。 write()方法调用参数错误:Python文件对象的write()方法仅接受1个字符串类型参数,代码中同时传入了字符串、浮点数、整数三个不同类型的参数,会直接触发TypeError,导致写入操作失败。- 裸异常捕获吞掉了具体错误:两个函数都用了不指定异常类型的裸
except,会把所有运行时错误全部拦截,既不打印具体错误信息,也不做针对性处理,导致错误被掩盖,最终表现为跳回主菜单打印无效操作提示。
修复方案
- 删除
add_item()中无意义的user_addition = input("")语句,去掉不必要的输入阻塞。 - 修正文件写入逻辑,先将商品名称、价格、库存拼接为格式统一的字符串(非字符串类型先做类型转换),再传入
write()方法,建议打开文件时指定encoding="utf-8"避免中文乱码。 - 替换裸
except为具体异常捕获,避免吞掉非预期错误,方便后续排查问题。
修复后的核心代码参考:
def user_interface_menu(): while True: try: print(""" -------------------------------------------------------------- Menu -------------------------------------------------------------- 1 - Show one item information 2 - Show all stock information 3 - Add item 4 - Update item 5 - Remove item 6 - Save and exit 7 - Exit without save""") user_action = int(input("Action - ")) if user_action not in (1, 2, 3, 4, 5, 6, 7): print("Please choose a valid action!") elif user_action == 1: one_item_information() elif user_action == 2: all_stock_information() elif user_action == 3: add_item() elif user_action == 4: update_item() elif user_action == 5: remove_item() elif user_action == 6: save_exit() elif user_action == 7: exit_no_save() except ValueError: # 仅捕获菜单输入类型错误,不吞其他异常 print("Please choose a valid action!") def add_item(): try: stock_name = input(""" Please state the name of the product. - """).strip() price_estimate = float(input(""" Please state the estimated price of the product. - """).strip()) stock_quantity = int(input(""" Please state the quantity of the product. - """).strip()) print("") print("New item Added! - ", end="") print(stock_name, price_estimate, stock_quantity) with open("store_stock.txt", "a", encoding="utf-8") as f: # 拼接为逗号分隔的字符串,可根据需要调整分隔符 f.write(f"{stock_name},{price_estimate},{stock_quantity}\n") except ValueError: print("输入格式错误:价格请输入数字,库存请输入整数") except Exception as e: print(f"商品添加失败:{str(e)}")
内容的提问来源于stack exchange,提问作者Sprinklerasian
相关产品推荐
相关产品推荐

