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

Python中appendLift方法无法更新JSON文件的技术问题

问题排查与修复

核心问题分析

你的程序无法更新JSON文件,主要由以下几个bug导致:

  • 菜单输入逻辑缺失:选择「更新训练量」后,程序仅定义了第二个菜单的文本,但没有获取用户的选择输入,直接复用了之前的reply值,导致逻辑跳转到卧推更新的代码,但实际流程不符合预期。
  • 键名不匹配:调用appendLift时传入的是'Benchpress',但JSON文件中存储的键是'Benchpress weight',导致if lift in liftsDictJson条件不成立,完全跳过了更新逻辑。
  • 异常处理不完整:当输入的重量无法转为整数时,程序仅打印错误但未终止方法执行,后续代码仍会继续运行,可能引发潜在问题。

修复后的完整代码

import json
from os.path import exists as file_exists


class Trainee():
    def __init__(self):
        self.liftsDict = {
            'Benchpress weight': [],
            'Press weight': [],
            'Squat weight': [],
            'Deadlift weight': []
        }

    def appendLift(self, lift, weight):
        with open('user.json', 'r') as f:
            data = json.load(f)
            liftsDictJson = data['liftsDict']
            
            # 拼接正确的键名,匹配JSON中的存储格式
            lift_key = f"{lift.title()} weight"
            try:
                weight = int(weight)
            except ValueError:
                print(f'{weight} 不是有效数字,请重新输入')
                return  # 异常后直接返回,避免后续无效操作
            
            if lift_key in liftsDictJson:
                liftsDictJson[lift_key].append(weight)
                print(f'\n{lift_key} 已更新为 {weight}')
        
                with open('user.json', 'w') as f:
                    json.dump(data, f, indent=4)
            else:
                print(f'未找到训练项:{lift_key}')

    def toJSON(self):
        with open('user.json', 'w') as f:
            json.dump(self.__dict__, f, indent=4)
    
    def setup(self):
        if not file_exists('user.json'):
            print('正在创建新用户文件...\n请填写初始训练重量:\n')              
            for key in self.liftsDict.keys():
                while True:
                    try:
                        value = int(input(f'{key}: '))
                        break
                    except ValueError:
                        print('请输入有效数字')
                self.liftsDict[key].append(value)
            self.toJSON()

# 初始化程序
user = Trainee()
user.setup()

while True:
    main_menu = """欢迎回来!
请输入数字选择操作:
[1]更新训练重量
[2]退出
: """
    reply = input(main_menu)
    if reply == '1':
        lift_menu = """选择要更新的训练项:
[1]卧推 3x5
[2]推举 3x5
[3]深蹲 3x5
[4]硬拉 1x5
[5]背部训练
: """
        lift_choice = input(lift_menu)  # 获取第二个菜单的用户选择
        if lift_choice == '1':
            weight_input = input('输入卧推3x5的新重量:')
            user.appendLift('Benchpress', weight_input)
        elif lift_choice == '2':
            weight_input = input('输入推举3x5的新重量:')
            user.appendLift('Press', weight_input)
        elif lift_choice == '3':
            weight_input = input('输入深蹲3x5的新重量:')
            user.appendLift('Squat', weight_input)
        elif lift_choice == '4':
            weight_input = input('输入硬拉1x5的新重量:')
            user.appendLift('Deadlift', weight_input)
        elif lift_choice == '5':
            print('背部训练暂未支持')
        else:
            print('无效选项,请重新选择')
    elif reply == '2':
        print('程序已退出')
        break
    else:
        print('无效选项,请重新选择')

关键修复点说明

  1. 完善菜单输入逻辑:新增lift_choice = input(lift_menu),正确获取用户对训练项的选择,避免逻辑混乱。
  2. 匹配键名:在appendLift方法中通过lift_key = f"{lift.title()} weight"拼接正确的键名,确保与JSON文件中的存储键一致。
  3. 增强异常处理:输入重量无效时,打印错误后直接return终止方法,避免后续无效代码执行;初始化阶段也添加了循环输入,确保用户输入有效数字。
  4. 扩展菜单分支:补全了其他训练项的更新逻辑,同时增加无效选项的提示,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 06:36:11