-1
我正在用Python编写一个脚本,而不是真正的cicle,我怎样才能让我的脚本对每个cicle采用相同的文件abc123.json并修改一些变量在里面?如何使python写入json读取和写入每个cicle的相同文件
我正在用Python编写一个脚本,而不是真正的cicle,我怎样才能让我的脚本对每个cicle采用相同的文件abc123.json并修改一些变量在里面?如何使python写入json读取和写入每个cicle的相同文件
如果我正确理解你的问题,你需要读取一个名为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共享同一个密钥。如果他们没有,你的函数将需要弄清楚如何匹配数据结构之间的键。
请提供一些你已经试过的代码 – Slam
我不知道“真正的cicle”是什么意思,但你可能想要将JSON文件加载到Python对象中,进行所有修改,然后转储返回到JSON。 –