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
import pickle
# define the class before unpickle
class Bird(object):
have_feather = True
way_of_reproduction = 'egg'
fn = 'a.pkl'
with open(fn, 'r') as f:
summer = pickle.load(f) # read file and build object