可以使用json.dumps()
函数将字典转换为可读性较好的字符串,然后将该字符串保存到文件中。加载时,再使用json.loads()
函数将字符串还原为字典。示例代码如下: 将字典数据保存为可读性较好的文件:
pythonCopy code
import json data = {'name': 'Alice', 'age': 20, 'gender': 'female'} with open('data.txt', 'w') as f: json.dump(data, f, indent=4, sort_keys=True)
使用indent
参数指定缩进空格数,使用sort_keys
参数指定是否按照键名排序。 将文件加载到字典:
pythonCopy code
import json with open('data.txt', 'r') as f: data_str = f.read() data = json.loads(data_str) print(data) # 输出:{'age': 20, 'gender': 'female', 'name': 'Alice'}
注意,使用json.loads()
函数加载时,需要将文件内容读取到字符串中再进行解析。