python读写json文件
无论是配置文件,还是传递数据,json在前端等地方出现得较多,用代码自动处理一些基本操作还是有必要的。JSON的格式,和Python中的字典差不多。
(1)读取json文件
import jsonfilename = '/root/config.json'
with open(filename, 'r', encoding='utf-8') as file:data = json.load(file)print(type(data)) # <class 'dict'>
(2)写入JSON文件
import jsonconfig_dict = {'speed': '1','mode': 'open','operation': 'add'}savefile = '/root/tick_config.json'
with open(savefile, 'w', encoding='utf-8') as f:print("设置配置文件...")json.dump(config_dict, f)
end