序列化:将对象的状态信息转换为可以存储或传输的形式的过程
pickle.dump(object, file) # 通过序列化的方式将一个对象保存到文件中(也可以说保存到硬盘中) pickle.load(file) # 从文件中读取字符串,并将它重构为原来的对象 pickle.dumps(object) # 通过序列化的方式将一个对象保存到字符串变量中(也可以说保存到内存中) pickle.loads(string) # 从字符串变量中读取字符串,并将它重构为原来的对象
In [1]: dict = {‘a‘:1, ‘b‘:2} In [2]: import pickle In [3]: with open(‘/tmp/1.pickle‘, ‘wb‘) as fd: # 将一个字典对象保存到文件中 ...: pickle.dump(dict, fd) ...: In [4]: with open(‘/tmp/1.pickle‘, ‘r‘) as fd: # 从文件中读取字符串,并将它重构为原来的对象 ...: d = pickle.load(fd) ...: print d ...: {‘a‘: 1, ‘b‘: 2}
In [1]: dict = {‘a‘:1, ‘b‘:2} In [2]: import pickle In [3]: a1 = pickle.dumps(dict) # 将一个字典对象保存到字符串变量中 In [4]: a2 = pickle.loads(a1) # 从字符串变量中读取字符串,并将它重构为原来的对象 In [5]: a2 Out[5]: {‘a‘: 1, ‘b‘: 2}