json和pickle的功能是对数据进行序列化
将对象转换为可通过网络传输或可以存储到本地磁盘的数据格式(如:XML、JSON或特定格式的字节串)的过程称为序列化;反之,则称为反序列化
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">import json
list1=[1,2,3,"hello world"]
data1=json.dumps(list1)
print(data1)#[1,"hello world"]
dict1={"one":1,"two":2,"three":3}
data2=json.dumps(dict1)
print(dict1)#{'one': 1,'two': 2,'three': 3}
data1=json.loads(data1)
print(data1)#[1,'hello world']
data2=json.loads(data2)
print(data2)#{'one': 1,'three': 3}
print(data2["one"])#1
dump和load
这两种方法可将序列化的数据存到文本和读取文本中序列化的数据
with open("listfile","r") as f2:
data=json.load(f2)
print(data)
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">import pickle
class people:
def init(self,name,age):
self.name=name
self.age=age
sfencs=people("sfencs",19)
data=pickle.dumps(sfencs)
print(data)#b'x80x03cmainnpeoplenqx00)x81qx01}qx02(Xx04x00x00x00nameqx03Xx06x00x00x00sfencsqx04Xx03x00x00x00ageqx05Kx13ub.'
data=pickle.loads(data)
print(data)#<main.people object at 0x0000029D8402DDA0>
pickle和json同样支持dump,load,dumps,loads方法
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">import shelve
with shelve.open("shelvefile") as f:
f["one"]=1
f["two"]=2
这里直接保存到了文件中,生成了3个文件shelvefile.bak,shelvefile.dat,shelvefile.dir
with shelve.open('shelvefile') as f:#只使用shelvefile名字即可
print(f["one"])#1
for key,value in f.items():
print(key,': ',value)
one : 1
#two : 2
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|