如何让 python 写入 json 为每个圈子读取和写入相同的文件

how to make python write json read and write same file for each cicle

我正在 Python 中编写一个脚本来做一些真正的 cicle,我怎样才能让我的脚本为每个 cicle 使用相同的文件 abc123.json 并修改其中的一些变量?

如果我对你的问题的理解正确,你想读取本地硬盘驱动器上某处名为 abc123.json 的文件,该文件可通过路径访问并修改该键的值(或更多)json 文件,然后重新写入。 我正在粘贴我刚才使用的一些代码示例,希望它能有所帮助

import json
from collections import OrderedDict
from os import path

def change_json(file_location, data):
    with open(file_location, 'r+') as json_file:
        # I use OrderedDict to keep the same order of key/values in the source file
        json_from_file = json.load(json_file, object_pairs_hook=OrderedDict)
        for key in json_from_file:
            # make modifications here
            json_from_file[key] = data[key]
        print(json_from_file)
        # rewind to top of the file
        json_file.seek(0)
        # sort_keys keeps the same order of the dict keys to put back to the file
        json.dump(json_from_file, json_file, indent=4, sort_keys=False)
        # just in case your new data is smaller than the older
        json_file.truncate()

# File name
file_to_change = 'abc123.json'
# File Path (if file is not in script's current working directory. Note the windows style of paths
path_to_file = 'C:\test'

# here we build the full file path
file_full_path = path.join(path_to_file, file_to_change)

#Simple json that matches what I want to change in the file
json_data = {'key1': 'value 1'}
while 1:
    change_json(file_full_path, json_data)
    # let's check if we changed that value now
    with open(file_full_path, 'r') as f:
        if 'value 1' in json.load(f)['key1']:
            print('yay')
            break
        else:
            print('nay')
            # do some other stuff

观察:上面的代码假定您的文件和 json_data 共享相同的密钥。如果他们不这样做,您的函数将需要弄清楚如何匹配数据结构之间的键。