【问题标题】:Appending data to JSON file with python?使用python将数据附加到JSON文件?
【发布时间】:2017-08-24 18:54:19
【问题描述】:

我制作了一个小型 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')方法吗?
  • 我不确定,但我会尝试。谢谢,我会告诉你它是否有效。
  • 如果没有,有这个post 似乎回答了这个问题。

标签: json python-3.x


【解决方案1】:

所以文件模式='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()

因此,当您将文件设置为 mode = 'w' 然后第一次执行 for 循环时,数据会完美地进入文件,而当第二次执行 for 循环时,数据会被之前的文件覆盖file.So file mode='a' 是一个过程,其中数据被添加/附加到文件中 n 次 for 循环运行

【讨论】:

  • 你所做的工作,它并没有覆盖,虽然它正在这样做:{“约翰”:{“姓”:“某姓”,“年龄”:“27”}}{“ Bob": { "surname": "Some other surname", "age": " 34" } }
  • 因此,当您将文件设置为 mode = 'w' 然后第一次执行 for 循环时,数据会完美地进入文件,而当第二次执行 for 循环时,数据会被覆盖file.So file mode='a' 中先前存在的数据是一个过程,其中数据被添加/附加到文件中 n 次 for 循环运行
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 2018-05-14
    • 2021-10-01
    • 2018-02-22
    • 2012-10-11
    • 2022-01-06
    相关资源
    最近更新 更多