一.写文件
info={"name":"李小龙",'age':66,'love':"cat"}
fp=open('testdict1.txt','w+',encoding='utf-8')
fp.write(info)
ls=list('1234567890')
# print(ls)
fp=open('test.txt','w+')
# # json.dump(ls,fp)
fp.write(ls)
错误原因:列表和字典不能直接写入文件
solution:用json.dump
改写:
ls=list('1234567890')
# print(ls)
fp=open('test.txt','w+')
json.dump(ls,fp)
改写:
info={"name":"李小龙",'age':66,'love':"cat"}
fp=open('testdict1.txt','w+',encoding='utf-8')
json.dump(info,fp)
success
但是:中文乱码
解决方法:
呈现:
二.读取文件
fp=open('test.txt','r+')
l=fp.read()
print(l)
print(type(l))
fp=open('testdict1.txt','r+')
dict=fp.read()
print(dict)
print(type(dict))
读取出来都是字符串
解决:
fp=open('testdict1.txt','r+')
dict=json.load(fp)
print(dict)
print(type(dict))
三.tips
info={"name":"李小龙",'age':66,'love':"cat"} fp=open('testdict1.txt','w+',encoding='utf-8') fp.write(json.dumps(info,ensure_ascii=False)) fp=open('testdict1.txt','r+') dict=json.load(fp) print(dict) print(type(dict)) #