Python中,对象也可以按文本方式存储到文件中,对应包为pickle
#encoding:utf8
import pickle
class Test(object):
a = 1
# 实例化对象,并进行存储
mTest = Test()
pickleStr = pickle.dumps(mTest)
f = open("file.txt","w")
f.write(pickleStr)
# 从文件中取出对象
f = open("file.txt","r")
str = f.read()
mTest = pickle. loads(str)
存储也可以采用dump方法,免去了写这一行代码
mTest = Test()
f = open("file.txt","w")
pickle.dump(mTest,f)
同样,读取可采用load方法
f = open("file.txt","r")
mTest = pickle. loads(f)
还有一个包 cPickle,使用方法和pickle一样,速度比 pickle快1000倍。导包时,只需使用import cPickle as pickle即可