[英]Copy JSON file then append it and a dictionary to another JSON file
我有一個現有的JSON文件,一個新的JSON文件以及一個現有的Python字典。 我想做的是將現有JSON文件中的數據復制到新的JSON文件中,然后將字典附加到新的JSON文件中。
mydict = {'a':1, 'b':2, 'c':3}
我的JSON文件看起來像Python字典:
{'hi': 4, 'bye' : 5, 'hello' : 6}
到目前為止,我有:
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.
我希望最終結果是一個包含現存的mydict
內容的字典。 另外,如果我將其轉換為函數,我希望能夠始終保留last.json中已經存在的內容,並僅追加一行新數據。
您可以像這樣加載更新並寫回文件:
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"))
將現有的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.