参考链接:https://blog.csdn.net/u014386899/article/details/102575547
# -*- coding:utf-8 -*-
import json
jsonpath = 'test.txt'
data = [('水果', ['apple', 'banana']),
{'蔬菜': {'绿色': '菠菜'}}
]
#data = json.dumps(data, indent=2) # indent 表示缩进
with open(jsonpath, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
with open(jsonpath, 'r', encoding='utf-8') as f:
load_dict = json.load(f)
print(load_dict)
需要注意的是,调用 json.dump(data, f, ensure_ascii=False, indent=2) 之前,不要调用 json.dumps(data, indent=2)去加工data变量 ,否则写入文件会有很多'\n',' \" '非常不好看,而且test.txt文本里敲个换行,json.load()就报错。
生成的test.txt文件内容如下,并支持改动该文件排版读入到程序:
[
[
"水果",
[
"apple",
"banana"
]
],
{
"蔬菜": {
"绿色": "菠菜"
}
}
]