如何使python write json对每个ci读写相同的文件

2024-04-25 22:30:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个脚本来执行一段真正的cicle,如何使脚本为每个cicle获取相同的abc123.json文件并修改其中的一些变量?在


Tags: 文件脚本jsoncicleabc123
1条回答
网友
1楼 · 发布于 2024-04-25 22:30:57

如果我正确地理解了您的问题,您希望读取本地硬盘上某个地方名为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\u数据共享相同的键。如果它们不匹配,那么您的函数将需要找出如何在数据结构之间匹配键。在

相关问题 更多 >