使用Python将数据添加到JSON文件中?

3

我做了一个小型的Python程序,将一些字符串输入写入JSON文件:

import json

while True:
    name = input('What is your name?')
    surname = input('What is your surname')
    age = input('How old are you?')

    with open("info_.json", "w") as data:
        information = {name: {'surname': surname, 'age': age}}
        data.write(json.dumps(information))
        data.close()

    with open("info_.json", "r") as info_read:
        dict_info = json.loads(info_read.read())
        name_d = dict_info.get(name)
        print(name_d)

它完美地工作了,尽管在循环的第二次,输入会覆盖第一次写入的信息。是否有一种方法可以在不覆盖的情况下添加更多数据到文件中? 谢谢


难道没有 with open("info_.json", 'a') 方法吗? - pstatix
我不确定,但我会尝试一下。谢谢,如果成功了我会告诉你的。 - Oqhax
如果没有,这篇帖子似乎回答了这个问题。 - pstatix
2个回答

8

因此,文件模式=“r”是读取文件,文件模式=“w”是写入文件,在for循环中,当您开始循环多次时,它应该被附加,即文件模式=“a”。如果使用“w”,则会尝试覆盖文件中现有的文本。

    with open("info_.json", "a") as data:
        information = {name: {'surname': surname, 'age': age}}
        data.write(json.dumps(information))
        data.close()

因此,当您将文件模式设置为“w”并执行第一次for循环时,数据完美地进入文件,当第二次执行for循环时,数据将覆盖先前在文件中存在的数据。 因此,文件模式为“a”的过程是,在for循环运行n次时,数据被添加/附加到文件中。


你所做的是有效的,它没有覆盖原有内容,尽管它正在执行以下操作:{ " John": { "surname": " 某个姓氏", "age": " 27" } }{ " Bob": { "surname": " 另一个姓氏", "age": " 34" } } - Oqhax
因此,当您将文件模式设置为“w”,然后第一次执行for循环时,数据完美地进入文件,当第二次执行for循环时,数据将覆盖先前存在的文件中的数据。因此,文件模式“a”是一个过程,在该过程中,数据在for循环运行n次时添加/附加到文件中。 - Chetan_Vasudevan
它应该加载旧数据并将新数据附加到其中,然后覆盖文件。当使用JSON时,没有办法进行追加,因为追加不知道文件是JSON。 - urek mazino

1

一个人不能简单地将内容添加到 JSON 文件中。

你需要先加载所有的 JSON 数据,然后在其上进行追加并将其写回文件。

import json

json_path = "info_.json"

def write_json(data, filename): 
    """Write json file with provided data"""
    with open(filename,'w') as f: 
        json.dump(data, f, indent=4) 


def print_user_info(name):
    """Read json data file, print specified user"""
    with open(json_path, "r") as info_read:
        info_data = json.loads(info_read.read())
        info_data = dict(info_data)
        user_data = info_data.get(name)
        print(f"{name} : {user_data}")


def update_user_info(name, surname, age):
    """Fetch existing json data, append to it, write to file and print new user details from file"""
    with open(json_path, "r") as info_fp:
        # Read existing data and append to new data it
        info_data = json.load(info_fp)
        info_data[name] = {'surname': surname, 'age': age}

        # Write updated data
        write_json(info_data, filename=json_path)

        # Print new user details from json file
        print_user_info(name)


# Function to take user inputs   
def new_user_input():
    """Take user inputs for new user data, update that into json data file"""
    name = input('What is your name? ')
    surname = input('What is your surname? ')
    age = input('How old are you? ')

    update_user_info(name, surname, age)


if __name__ == '__main__':
    new_user_input()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接