python pickle 序列化类
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python pickle 序列化类相关的知识,希望对你有一定的参考价值。
python pickle 序列化类
# coding:utf-8 try: import cPickle as pickle except ImportError: import pickle class PickleVar(object): __doc__ = ‘‘‘序列化操作类‘‘‘ def __init__(self): print (‘------------------------------------------------------‘) def dump(self, data, fileName): with open(fileName, "wb") as f: pickle.dump(data, f) def load(self, fileName): with open(fileName, ‘rb‘) as f: return pickle.load(f) def __del__(self): print (‘------------------------------------------------------‘) if __name__ == ‘__main__‘: # 生成随机数 data = range(10) # print pickle.dumps(data) # print pickle.loads(pickle.dumps(data)) ‘‘‘注意:dump和dumps是有区别的,dump是保存到文件,而dumps只是生成序列化后的字符串‘‘‘ p = PickleVar() # 存入变量data p.dump(data, ‘file‘) print p.load(‘file‘)
以上是关于python pickle 序列化类的主要内容,如果未能解决你的问题,请参考以下文章
python代码学习day03-序列化学习pickle及json
保存数据到文件的模块(configparser,json,pickle,shelve,xml)_python