JSON加载正常但无法完整保存,出现int不可迭代TypeError问题
问题分析与解决
核心问题1:money无法保存
你遇到的money不能保存的原因很直接:
self.money是从self.data['money']复制出来的整数(不可变类型),修改self.money只是改变了这个独立变量的值,并不会同步到self.data字典里。而你保存的是self.data,所以原数据里的money根本没更新。
核心问题2:TypeError: 'int' object is not iterable
你之前尝试拼接变量时触发的这个错误,大概率是误将money这个整数当成了可迭代对象(比如试图用for循环遍历、或者传给需要可迭代对象的函数),比如写了sum(self.money)这类代码——整数没法迭代,自然报错。
修复代码
只需修改关键同步逻辑,就能解决问题:
import json, sys PURCHASE_PRICES = { 'wood': 4, 'apple': 2, 'corn': 10, 'tomato': 20 } class Test: def __init__(self): save_information = { 'item_inventory': { 'wood': 1, 'apple': 1, 'corn': 1, 'tomato': 1 }, 'money': 500 } try: print('save found') with open('save.txt') as save_file: save_information = json.load(save_file) except: print('no save file found') with open('save.txt', 'w') as save_file: json.dump(save_information, save_file) with open('save.txt', 'r') as save_file: save_information = json.load(save_file) self.data = save_information self.item_inventory = self.data['item_inventory'] self.money = self.data['money'] print(self.item_inventory) print(self.money) current_item = input('enter item to buy "wood", "apple", "tomato" or "corn" \n> ') amount_to_buy = input(f'how many {current_item} would you like to buy\n> ') item_price = PURCHASE_PRICES[current_item] amount = int(amount_to_buy) total_cost = item_price * amount if self.money >= total_cost: self.item_inventory[current_item] += amount self.money -= total_cost print(self.item_inventory) print(self.money) action = input('press "q" to save and exit\n> ') if action == 'q': # 关键:把更新后的money同步回self.data self.data['money'] = self.money with open('save.txt', 'w') as save_file: json.dump(self.data, save_file) sys.exit() if __name__ == '__main__': test = Test() # 原代码的test()调用会报错,Test类无__call__方法,实例化即执行所有逻辑,故删除
额外优化说明
- 提前转换购买数量为整数并计算总成本,避免重复类型转换,代码更简洁;
- 修正了输入提示里的标点错误;
- 移除了多余的
test()调用,避免触发TypeError: 'Test' object is not callable错误。
内容的提问来源于stack exchange,提问作者Alex Haynes
相关产品推荐
相关产品推荐

