json和pickle

json:用于列表和字典的数据存储和传输,无法处理集合


# 把一个一个字典放文件里,再读出来
import json
dic = {'k1':'v1',
       'k2':'v2'}
str_dic = json.dumps(dic)
f = open('a.txt','a')
f.write(str_dic + '\n')
f.write(str_dic + '\n')
f.write(str_dic + '\n')
f.close()

f = open('a.txt','r')
for line in f:
    dic = json.loads(line)
    print(dic,type(dic))
f.close()



s = {'lis':['helo','脏水'],'ruguo':'zidian',1:4444}
print(json.dumps(s,indent=4,ensure_ascii=False))

pickle:只在python使用,可以处理所有数据类型

# pickle 写入文件方式是bytes
import pickle

dic = {'k1':'v1',
       'k2':'v2'}

p = pickle.dumps(dic)
print(p)
f = open('a.txt','ab')
f.write(p)
f = open('a.txt','rb')
dic = f.read()
dic = pickle.loads(dic)
print(dic)
f.close()

pickle可以连续读出pickle数据文件

import pickle

dic1 = {'k1':'v1'}
dic2 = {'k2':'v1'}
dic3 = {'k3':'v1'}
dic4 = {'k4':'v1'}


with open('a.txt','ab') as f:
    pickle.dump(dic1,f)
    pickle.dump(dic2,f)
    pickle.dump(dic3,f)
    pickle.dump(dic4,f)

with open('a.txt', 'rb') as f:
    while True:
        try:
            dic = pickle.load(f)
            print(dic)
        except Exception as e:
            print(e)
            break
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值