对象持久化
将当前的进度和状态存储起来(序列化)
将存储的数据读取出来(反序列化)
常见技术:
扁平文件;pickle;shelve;数据库;ORM
扁平文件
存储为文本文件时,存储为纯文字,当反序列化时需要进行一个形式转化的工作。
序列化过程
l = [1,2,3]
def t():
with open('1024.txt','w',encoding='utf8') as f:
f.write(str(l))
print('down')
def r():
with open('1024.txt','r',encoding='utf8') as f:
x = f.read()
x[0] = 99
print(x)
if __name__ =='__main__':
t()
r()
结果:
down
抛异常
此时存储的l只是文本,反序列化要用eval将其转化为列表
l = [1,2,3]
def t():
with open('1024.txt','w',encoding='utf8') as f:
f.write(str(l))
print('down')
def r():
with open('1024.txt','r',encoding='utf8') as f:
x = eval(f.read())
x[0] = 99
print(x)
if __name__ =='__main__':
t()
r()
结果:
down
[99, 2, 3]
pickle
dumps可以将对象存储为字符串(字符),用loads反序列化
import pickle
d = {'a':1,'b':2}
s = pickle.dumps(d)
d
{'a': 1, 'b': 2}
s
b'\x80\x03}q\x00(X\x01\x00\x00\x00aq\x01K\x01X\x01\x00\x00\x00bq\x02K\x02u.'
p
{'a': 1, 'b': 2}
type(p)
<class 'dict'>
还可以将对象序列化存储到文件里(以二进制的形式)
import pickle
d = {'a':1,'b':2}
pickle.dump(d,open('pickle_db','wb'))
p = pickle.load(open('pickle_db','rb'))
p
{'a': 1, 'b': 2}
type(p)
<class 'dict'>
pickle最大的问题在于当把多个对象存储在一个文件中时,要注意
shelve(可用文件存储多个数据)
import shelve
l = [1,2,3]
d = {'x':'a','y':'b'}
db = shelve.open('shelve_ld')
db['l'] = l
m = db['l']
m
[1, 2, 3]
db['d'] = d
len(db)
2
import shelve
class haha:
def __init__(self,a,b = 0,c = None):
self.a = a
self.b = b
self.c = c
def __str__(self):
return self.a
def write():
s = haha('bala','lala')
db = shelve.open('haha_db')
db['s'] = s
db.close()
def read():
db = shelve.open('haha_db')
z = db['s']
print(z)
if __name__ == '__main__':
write()
read()
结果:bala