Python向JSON文件追加数据报错:'str' object has no attribute 'append'
解决JSON文件追加数据时的
'str' object has no attribute 'append'错误 你的问题核心是:file.read()读取到的information是字符串类型,而字符串没有append方法——只有列表(list)才能用这个方法来追加元素。要正确实现JSON数据追加,得先把读取到的JSON字符串转换成Python的列表对象,操作完成后再转回JSON格式写回文件。
具体修改思路
- 用
json.load()替代直接read(),把文件中的JSON字符串解析成Python列表(前提是你的db.json存储的是数组结构,比如[]或[{"firstName": "...", ...}]) - 处理文件不存在或为空的异常情况,避免程序报错
- 使用
with语句管理文件,自动关闭文件,避免资源泄漏 - 追加数据后,用
json.dump()把更新后的列表写回文件,同时可以加indent参数让JSON格式更易读
修改后的完整可运行代码
import json def addContact(): # 初始化存储列表 information = [] try: # 读取现有数据并解析为Python列表 with open("db.json", "r") as file: information = json.load(file) except (FileNotFoundError, json.JSONDecodeError): # 文件不存在/为空/格式错误时,保持空列表 pass firstName = input("请输入名字: ") lastName = input("请输入姓氏: ") phoneNumber = input("请输入电话号码: ") jsonAddData = { "firstName": firstName, "lastName": lastName, "phoneNumber": phoneNumber } # 向列表追加新联系人 information.append(jsonAddData) # 将更新后的列表写回JSON文件 with open("db.json", "w") as file: json.dump(information, file, indent=4) print("联系人已成功添加") def listRecords(): try: with open("db.json", "r") as file: contacts = json.load(file) if not contacts: print("暂无联系人记录") return print("所有联系人:") for idx, contact in enumerate(contacts, 1): print(f"{idx}. {contact['firstName']} {contact['lastName']} - {contact['phoneNumber']}") except (FileNotFoundError, json.JSONDecodeError): print("暂无联系人记录") def findFirst(): search_name = input("请输入要查找的名字: ") try: with open("db.json", "r") as file: contacts = json.load(file) for contact in contacts: if contact["firstName"].lower() == search_name.lower(): print(f"找到联系人: {contact['firstName']} {contact['lastName']} - {contact['phoneNumber']}") return print(f"未找到名字为{search_name}的联系人") except (FileNotFoundError, json.JSONDecodeError): print("暂无联系人记录") def delFirst(): search_name = input("请输入要删除的名字: ") try: with open("db.json", "r") as file: contacts = json.load(file) # 查找并删除第一个匹配项 for idx, contact in enumerate(contacts): if contact["firstName"].lower() == search_name.lower(): del contacts[idx] with open("db.json", "w") as file: json.dump(contacts, file, indent=4) print(f"已删除联系人: {contact['firstName']} {contact['lastName']}") return print(f"未找到名字为{search_name}的联系人") except (FileNotFoundError, json.JSONDecodeError): print("暂无联系人记录") def commandFunction(): while True: print("\n请选择操作选项:") print("1. 添加联系人") print("2. 查看所有记录") print("3. 查找第一个匹配的联系人") print("4. 删除第一个匹配的联系人") print("5. 退出") try: userInput = int(input("请输入选项编号: ")) except ValueError: print("请输入有效的数字编号") continue if userInput == 1: addContact() elif userInput == 2: listRecords() elif userInput == 3: findFirst() elif userInput == 4: delFirst() elif userInput == 5: print("退出程序") break else: print("请输入1-5之间的有效编号") commandFunction()
额外优化说明
- 新增了异常处理,覆盖文件不存在、空文件、JSON格式错误等场景
- 完善了原代码中未实现的
listRecords、findFirst、delFirst函数,让程序具备完整功能 - 调整了菜单提示和输入逻辑,提升用户体验
内容的提问来源于stack exchange,提问作者Christian McCulley
相关产品推荐
相关产品推荐

