1、pickle包
(1)、将内存中的对象转换成为文本流: import pickle
# define class
class Bird(object):
have_feather = True
way_of_reproduction = 'egg'
summer = Bird() # construct an object
picklestring = pickle.dumps(summer) # serialize object
使用pickle.dumps()方法可以将对象summer转换成了字符串 picklestring(也就是文本流)。随后我们可以用普通文本的存储方法来将该字符串储存在文件(文本文件的输入输出)。
当然,我们也可以使用pickle.dump()的方法,将上面两部合二为一:import pickle
# define class
class Bird(object):
have_feather = True
way_of_reproduction = 'egg'
summer = Bird() # construct an object
fn = 'a.pkl'
with open(fn, 'w') as f: # open file with write-mode
picklestring = pickle.dump(summer, f) # serialize and save object
对象summer存储在文件a.pkl
(2)、重建对象
首先,我们要从文本中读出文本,存储到字符串 (文本文件的输入输出