数据处理不要保存到文件,要保存到json
参考:[python读写json、格式化写入json文件_python 将json 格式化 load_尤达c的博客-CSDN博客]
常用方法
#读取json文件->dict
import json
with open('states.json','r') as f:
data = json.load(f)
print(type(data))
#<class 'dict'>
#str_json->dict
new_dict = json.loads(json_str)
print(new_dict)
print(type(new_dict))
#<class 'dict'>
#dict->json文件
with open('countries_exported.json', 'w') as f:
json.dump(country, f)
#dict->str_json
test_dict = {'one':1, 'two':{2.1:['a', 'b']}
print(type(test_dict))
#dumps 将数据转换成字符串
json_str = json.dumps(test_dict)
print(json_str)
print(type(json_str))
#<class 'dict'>
#<class 'str'>
规范方法,好看.
json.dump(country, f, indent=4)
with open("json.json", 'w') as write_f:
write_f.write(json.dumps(load_dict, indent=4, ensure_ascii=False))