【问题标题】:How to add a new JSON data at the end of the existing data in python如何在 python 中现有数据的末尾添加新的 JSON 数据
【发布时间】:2022-11-25 17:25:12
【问题描述】:

我正在尝试根据用户输入填充一个 JSON 文件。 users.json 文件最初是空的,我可以注册第一个用户("Doe_Joh")。问题是当我运行程序并注册第二次使用时。里面的数据被数据替换了。我期望的是增量保存数据。我怎样才能做到这一点?

这是我的代码。

import json

class User:

        def register():

            first = input("Name: ")
            last = input("Last: ")
            username = input("Username: ")
            email = input("Email: ")
            user_data = {  username: [ {
                            "fname": first, 
                            "lname": last,
                            "username": username,
                            "email": email
                           }
                            
                        ]
                   } 
            with open("users.json", "w") as outfile:
             json.dump(user_data, outfile, indent=4)
                    
  

 
user1 = User
user1.register()

【问题讨论】:

  • 您可能希望以追加模式而不是写入模式打开文件open("users.json", "a")。但是整个数据不会是 json,而是每个用户一个接一个的 json。如果您想要单个 json,则必须读取整个文件并在将新用户添加到数据后再次写入。
  • 你好@Jay,谢谢你的回答。我可能更喜欢最后一个选项。但是 json.dumb 在那种情况下会有用吗?

标签: python json


【解决方案1】:

你可以通过两种方式做到这一点:

加载整个 user.json,在文件末尾添加一个新用户, 并保存一切。 或者尝试以追加模式打开 user.json:

 with open("users.json", "a") as outfile:
                 json.dump(user_data, outfile, indent=4)

注意open() 函数中的“a”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多