写入json
import json
# 写入json
all_res = {}
write_path = "E:/test_feature.json"
all_res["明天"] = "天气好"
with open(write_path, "w", encoding='utf-8') as f:
json.dump(all_res, f, ensure_ascii=False)
打开文件test_feature.json
,写入的内容为:
{"明天": "天气好"}
中文的写入 json.dump
需要加上ensure_ascii=False
参数。否则默认写入unicode
{"\u660e\u5929": "\u5929\u6c14\u597d"}
这里 查询不同编码之间的转换:
读取json
write_path = "E:/test_feature.json"
with open(write_path, encoding="utf-8") as f:
res = json.load(f)
print(type(res))
print(res['明天'])
读取文件时,需要加上encoding="utf-8"
,否则会出现错误UnicodeDecodeError: 'gbk' codec can't decode byte 0xbd in position 20: illegal multibyte sequence
<class 'dict'>
天气好
网友评论