我正在用Python编写一个脚本做一段时间真正的cicle,我如何让我的脚本为每个cicle采用相同的文件abc123.json并修改其中的一些变量?
答案 0 :(得分:0)
如果我正确理解你的问题,你想在本地硬盘驱动器上某处读取一个名为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共享相同的密钥。如果他们不这样做,你的函数将需要弄清楚如何在数据结构之间匹配键。