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

Python实现向已有JSON文件追加新用户数据的方法

解决用户增量保存问题

问题原因

你当前的代码每次注册用户时,直接以写入模式("w")打开users.json,会清空文件原有内容;并且每次只生成当前用户的字典,没有合并之前已保存的用户数据,导致新用户覆盖旧用户。

修改方案

要实现增量保存,需要先读取文件中已有的用户数据,将新用户信息合并进去后再写回文件。具体步骤:

  • 尝试读取users.json文件,若文件不存在或为空,初始化一个空字典
  • 将新注册的用户信息添加到这个字典中
  • 以写入模式将合并后的完整数据写回文件

另外,原代码中的register方法定义不符合类方法规范,这里一并修正为静态方法。

修改后的代码

import json

class User:
    @staticmethod
    def register():
        first = input("Name: ")
        last = input("Last: ")
        username = input("Username: ")
        email = input("Email: ")
        
        # 读取已有用户数据
        try:
            with open("users.json", "r") as infile:
                existing_users = json.load(infile)
        # 处理文件不存在或为空的异常情况
        except (FileNotFoundError, json.JSONDecodeError):
            existing_users = {}
        
        # 添加新用户到已有数据字典
        existing_users[username] = {
            "fname": first, 
            "lname": last,
            "username": username,
            "email": email
        }
        
        # 将合并后的数据写回文件
        with open("users.json", "w") as outfile:
            json.dump(existing_users, outfile, indent=4)

# 调用注册方法
User.register()

关键改动说明

  • 用try-except捕获文件不存在或解析失败的异常,避免程序崩溃
  • 读取原有用户数据到字典中,新用户直接以用户名作为键存入,结构更合理
  • 最终写入的是包含所有用户的完整字典,实现增量保存

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:25:30