简体   繁体   English

复制JSON文件,然后将其和字典附加到另一个JSON文件

[英]Copy JSON file then append it and a dictionary to another JSON file

I have an existing JSON file, a new JSON file to be made, and an existing Python dictionary. 我有一个现有的JSON文件,一个新的JSON文件以及一个现有的Python字典。 What I'm trying to do is copy over the data in my existing JSON file to my new JSON file and then append my dictionary to the new JSON file. 我想做的是将现有JSON文件中的数据复制到新的JSON文件中,然后将字典附加到新的JSON文件中。

mydict = {'a':1, 'b':2, 'c':3}

My JSON file looks like a Python dictionary: 我的JSON文件看起来像Python字典:

{'hi': 4, 'bye' : 5, 'hello' : 6}

So far, I have: 到目前为止,我有:

with open('existing.json', 'r') as old, open ('recent.json', 'a') as new:
  #This is where i get stuck on how to copy over the contents of existing.json, and how to append mydict as well.

I want the end result to be one dictionary containing the contents of existing.json and mydict . 我希望最终结果是一个包含现存的mydict内容的字典。 Also if I turn this into a function I want to be able to always keep the contents that are already in recent.json and just append a new line of data. 另外,如果我将其转换为函数,我希望能够始终保留last.json中已经存在的内容,并仅追加一行新数据。

You can load update and write back the file like this: 您可以像这样加载更新并写回文件:

import json

mydict = {'a':1, 'b':2, 'c':3}

data = json.load(open('existing.json'))
data.update(mydict)
json.dump(data, open('recent.json', "w"))

Load your existing JSON to a dictionary, then combine this loaded data with your dictionary and save combined data as JSON . 将现有的JSON加载到字典中,然后将该加载的数据与字典合并,然后将合并的数据另存为JSON

import json


def combine_json_with_dict(input_json, dictionary, output_json='recent.json'):
    with open(input_json) as data_file:
        existing_data = json.load(data_file)

    combined = dict(existing_data, **dictionary)

    with open(output_json, 'w') as data_file:
        json.dump(combined, data_file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM