持久化-pickle和shelve

序列化:数据转成文本的过程被称为“序列化”,即将对象状态转换为可保持或传输的格式的过程
反序列化:对应的,从序列化的格式中解析对象状态的过程被称为“反序列化”

pickle的使用方法:

- 需要导入pickle包

- pickle.dump()   #将数据写入到文件中

- pickle.load()  #将数据从文件中读出

- 文件中的内容要求是列表或元组

import pickle

test_data = ["save me", 123, 456, True]
f1 = open(r".vscode\project\test.txt", "wb")
pickle.dump(test_data, f1)  #存储文件中的数据
f1.close()

f2 = open(r".vscode\project\test.txt", 'rb')  #文件内容必须为pickle能够识别的
test_data = pickle.load(f2)
f2.close()
print(test_data)  #读取文件中的数据

shelve的使用方法:

- 类似于字典,用kv对保存数据,存取方式跟字典也类似,也可以像字典一样使用get来获取数据

- shelve.open和shelve.close()

- 和读写操作一样,打开后必须关闭

为什么在有json和pickle的情况下还要使用shelve:

使用json或者pickle持久化数据,能dump多次,但load的话只能取到最新的dump,因为先前的数据已经被后面dump的数据覆盖掉了,如果想要实现dump多次不被覆盖,就可以想到使用shelve模块,另外,写程序的时候如果不想用关系数据库那么重量级的操作去存储数据,也可以用到shelve。shelve模块可以持久化所有pickle所支持的数据类型。

import shelve

#如果系统中没有该文件则自动创建一个
shv = shelve.open(r'shv.db')

shv['one'] = 1
shv['two'] = 2
shv['three'] = 3

shv.close()

shv = shelve.open(r'shv.db')

try:
    print(shv['one'])
    print(shv['four'])
except Exception as e:
    print("找不到该key")
finally:
    shv.close()

#1
#找不到该key



猜你喜欢

转载自www.cnblogs.com/wjw2018/p/10540287.html