使用
Python处理json文件很简单,只需要import json
即可,所需要掌握的函数也只有以下四个。
json.dumps(obj):将python数据类型转化为str类型
json.dump(obj,fp):将python数据写入文件fp中
import json
dic = {'a': 'aa', 'b': 'bb', 'c': {'c1': 'cc', 'c2': 'cc'}}
with open('config.json', 'w') as f:
# 先转换成字符串再写入
config = json.dumps(dic)
f.write(config)
# 直接写入
json.dump(dic, f)
为了美观,我们一般加上参数config = json.dumps(dic, indent=4)
,首行缩进4个字符。
json.load(fp):从json文件中读取数据
json.loas(str):将str类型转换为python数据类型
# 一般是下面这种用法
with open('config.json', 'r') as f:
config = json.load(f)
# 这种很少用
config = json.loads(json.dumps(dic))
注意事项
有时候我们需要读取一个json文件,文件必须确保先被创建
if not os.path.exists('config.json'):
with open('config.json', 'w') as f:
f.write('{}') # 写入一个空字典,确保后面读取后不会出错
对配置进行改动后再保存,需要先清空配置文件
with open('config.json', 'r+') as f: # 这里只能用'r+'模式打开
config = json.load(f) # 读取json文件
config.pop('c') # 剔除参数
# 不加下面两句就会在文件末尾继续续写
f.seek(0) # 指针移到文件头
f.truncate() # 清空文件
json.dump(config, f, indent=2) # 写入新配置
或者采用下面的分开读取和写入的方法
with open('config.json', 'r') as f:
config = json.load(f) # 读取json文件
config.pop('c') # 剔除参数
with open('config.json', 'w') as f: # 'w'模式打开文件默认先清空
json.dump(config, f, indent=2) # 写入新配置