pickle
序列化为字符串
.dumps(obj): 将对象序列为字符串
.loads(s): 从字符串反序列化对象
例如
1 import pickle 2 3 person = {'name': 'Tom', 'age': 20} 4 s = pickle.dumps(person) 5 print(s) 6 # b'x80x03}qx00(Xx04x00x00x00nameqx01Xx03x00x00x00Tomqx02Xx03x00x00x00ageqx03Kx14u.' 7 p = pickle.loads(s) 8 print(p) 9 # {'name': 'Tom', 'age': 20}
序列化对象到文件
.dump(obj, file)
.load(file)
例如
1 import pickle 2 3 person = {'name': 'Tom', 'age': 20} 4 # 序列化对象到文件 5 pickle.dump(person, open('pickle_db', 'wb')) 6 p = pickle.load(open('pickle_db', 'rb')) 7 print(p) 8 # {'name': 'Tom', 'age': 20}
Shelve
.open('dbfile') 用shelve.open('dbfile') 打开文件
db['key'] = obj 给键‘key’赋值
len(db) 检查db的大小
del db['key']删除db字典中键为‘key’的键值对