使用python将数据附加到JSON文件?

时间:2017-08-24 18:54:19

标签: json python-3.x

我制作了一个小的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)

它工作得非常好,尽管第二次循环,输入会覆盖第一次写入的信息。有没有办法添加更多数据到文件,而不覆盖? 谢谢

2 个答案:

答案 0 :(得分:2)

所以档案模式=' 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'是一个过程,其中数据被添加/附加到文件中n次运行for循环

答案 1 :(得分:0)

一个不简单地附加到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()