python中的json模块可以将dict转str,str转dict,dict存储到文件中,文件中导入成dict
dict={'user':'john','sex':'male'}
str=json.dumps(dcit)#<class 'str'>
print(json.loads(str))#{'user': 'john', 'sex': 'male'}
#可以直接用字符串转换
str1='{"user":"john","sex":"male"}'
print(json.loads(str1))#{'user': 'john', 'sex': 'male'}
导出和导入文件的代码
str='{"user":"john","sex":"male"}'
with open('test.txt','w',encoding='utf-8') as fout:
json.dump(str,fout)
fout.close()
with open('test.txt','r',encoding='utf-8') as fout:
print(json.load(fout))
fout.close()
json还可以将dict的list转成str存到文件里,再用load可以读入成一个dict格式的list
with open('test.txt','w',encoding='utf-8') as f:
f.writelines(json.dumps([{'hello':'world'},{'hello':'world'},{'hello':'world'}]))
print(type(json.dumps([{'hello':'world'},{'hello':'world'},{'hello':'world'}])))
f.close()
with open('test.txt','r',encoding='utf-8') as f:
test_l=json.load(f)
print(type(test_l[0]))
f.close()