Python中pickle模块的使用方法-创新互联
Python中 pickle模块的使用方法?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
目前创新互联公司已为成百上千家的企业提供了网站建设、域名、虚拟空间、网站托管维护、企业网站设计、武陵源网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。用于序列化的两个模块
- json:用于字符串和Python数据类型间进行转换
- pickle: 用于python特有的类型和python的数据类型间进行转换
- json提供四个功能:dumps,dump,loads,load
- pickle提供四个功能:dumps,dump,loads,load
pickle可以存储什么类型的数据呢?
- 所有python支持的原生类型:布尔值,整数,浮点数,复数,字符串,字节,None。
- 由任何原生类型组成的列表,元组,字典和集合。
- 函数,类,类的实例
pickle模块中常用的方法有:
1. pickle.dump(obj, file, protocol=None,)
必填参数obj表示将要封装的对象
必填参数file表示obj要写入的文件对象,file必须以二进制可写模式打开,即“wb”
可选参数protocol表示告知pickler使用的协议,支持的协议有0,1,2,3,默认的协议是添加在Python 3中的协议3。
- Protocol version 0 is the original “human-readable” protocol and is backwards compatible with earlier versions of Python.
- Protocol version 1 is an old binary format which is also compatible with earlier versions of Python.
- Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. Refer to PEP 307 for information about improvements brought by protocol 2.
- Protocol version 3 was added in Python 3.0. It has explicit support for bytes objects and cannot be unpickled by Python 2.x. This is the default protocol, and the recommended protocol when compatibility with other Python 3 versions is required.
- Protocol version 4 was added in Python 3.4. It adds support for very large objects, pickling more kinds of objects, and some data format optimizations. Refer to PEP 3154 for information about improvements brought by protocol 4.
2. pickle.load(file,*,fix_imports=True, encoding="ASCII", errors="strict")
必填参数file必须以二进制可读模式打开,即“rb”,其他都为可选参数
3. pickle.dumps(obj):以字节对象形式返回封装的对象,不需要写入文件中
4. pickle.loads(bytes_object): 从字节对象中读取被封装的对象,并返回
pickle模块可能出现三种异常:
1. PickleError:封装和拆封时出现的异常类,继承自Exception
2. PicklingError: 遇到不可封装的对象时出现的异常,继承自PickleError
3. UnPicklingError: 拆封对象过程中出现的异常,继承自PickleError
应用:
# dumps功能 import pickle data = ['aa', 'bb', 'cc'] # dumps 将数据通过特殊的形式转换为只有python语言认识的字符串 p_str = pickle.dumps(data) print(p_str) 7 b'\x80\x03]q\x00(X\x02\x00\x00\x00aaq\x01X\x02\x00\x00\x00bbq\x02X\x02\x00\x00\x00ccq\x03e.
当前文章:Python中pickle模块的使用方法-创新互联
当前网址:http://ybzwz.com/article/csdiso.html