pickle — Python 对象序列化

模块 pickle 实现了对一个 Python 对象结构的二进制序列化和反序列化。 "pickling" 是将 Python 对象及其所拥有的层次结构转化为一个字节流的过程,而 "unpickling" 是相反的操作,会将(来自一个 binary file 或者 bytes-like object 的)字节流转化回一个对象层次结构。 pickling(和 unpickling)也被称为“序列化”, “编组” 1 或者 “平面化”。而为了避免混乱,此处采用术语 “封存 (pickling)” 和 “解封 (unpickling)”。

pickle 模块提供了以下方法,让封存过程更加方便:

pickle.dump(objfileprotocol=None*fix_imports=Truebuffer_callback=None)

将对象 obj 封存以后的对象写入已打开的 file object file。它等同于 Pickler(file, protocol).dump(obj)

参数 fileprotocolfix_imports 和 buffer_callback 的含义与它们在 Pickler 的构造函数中的含义相同。

在 3.8 版更改: 加入了 buffer_callback 参数。

pickle.dumps(objprotocol=None*fix_imports=Truebuffer_callback=None)

将 obj 封存以后的对象作为 bytes 类型直接返回,而不是将其写入到文件。

参数 protocolfix_imports 和 buffer_callback 的含义与它们在 Pickler 的构造函数中的含义相同。

在 3.8 版更改: 加入了 buffer_callback 参数。

pickle.load(file*fix_imports=Trueencoding='ASCII'errors='strict'buffers=None)

从已打开的 file object 文件 中读取封存后的对象,重建其中特定对象的层次结构并返回。它相当于 Unpickler(file).load()

Pickle 协议版本是自动检测出来的,所以不需要参数来指定协议。封存对象以外的其他字节将被忽略。

参数 filefix_importsencodingerrorsstrict 和 buffers 的含义与它们在 Unpickler 的构造函数中的含义相同。

在 3.8 版更改: 加入了 buffers 参数。

pickle.loads(data/*fix_imports=Trueencoding="ASCII"errors="strict"buffers=None)

重建并返回一个对象的封存表示形式 data 的对象层级结构。 data 必须为 bytes-like object

Pickle 协议版本是自动检测出来的,所以不需要参数来指定协议。封存对象以外的其他字节将被忽略。

参数 filefix_importsencodingerrorsstrict 和 buffers 的含义与它们在 Unpickler 的构造函数中的含义相同。

在 3.8 版更改: 加入了 buffers 参数。

class TextReader:
    """Print and number lines in a text file."""

    def __init__(self, filename):
        self.filename = filename
        self.file = open(filename)#注意要先open文件
        self.lineno = 0

    def readline(self):
        self.lineno += 1
        line = self.file.readline()
        if not line:
            return None
        if line.endswith('\n'):
            line = line[:-1]
        return "%i: %s" % (self.lineno, line)

    def __getstate__(self):
        # Copy the object's state from self.__dict__ which contains
        # all our instance attributes. Always use the dict.copy()
        # method to avoid modifying the original state.
        state = self.__dict__.copy()
        # Remove the unpicklable entries.
        del state['file']
        return state

    def __setstate__(self, state):
        # Restore instance attributes (i.e., filename and lineno).
        self.__dict__.update(state)
        # Restore the previously opened file's state. To do so, we need to
        # reopen it and read from it until the line count is restored.
        file = open(self.filename)
        for _ in range(self.lineno):
            file.readline()
        # Finally, save the file.
        self.file = file
>>> reader = TextReader("hello.txt")
>>> reader.readline()
'1: Hello world!'
>>> reader.readline()
'2: I am line number two.'
>>> new_reader = pickle.loads(pickle.dumps(reader))
>>> new_reader.readline()
'3: Goodbye!'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python对象序列化是指将Python对象转化为字节流的过程,以便在不同的系统之间传输或存储。通过序列化,我们可以将对象保存到磁盘上或通过网络发送给其他计算机。Python提供了pickle模块来实现对象序列化和反序列化。引用中的链接提供了一个关于序列化存储Python对象的示例。 在Python中,变量是对象的引用,可以用多个变量引用同一个对象。因此,通过pickle模块,我们可以轻松地将对象序列化到文件中,并在需要时进行反序列化。引用中提到,Python在处理经过pickle对象时非常方便。 我们可以使用pickle模块的dump()函数将对象保存到文件中,然后使用load()函数来读取文件并重新创建对象。在引用的代码示例中,我们可以看到定义了一个Student类,其中包含了初始化方法__init__()、保存方法save()和读取方法read(),分别用于初始化对象成员、将对象保存到文件和读取文件的内容。 当我们使用pickle.dump()将Student类的对象s1保存到文件时,可以使用pickle.load()来读取文件并返回一个Student类的对象。在引用的代码示例中,通过调用s1.save()将对象保存到文件,然后通过调用print(s1.read())来读取文件并返回对象。 综上所述,Python对象序列化是将Python对象转化为字节流的过程,可以通过pickle模块的dump()函数将对象保存到文件,再通过load()函数读取文件并返回对象。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Python中的对象序列化](https://blog.csdn.net/MixJet/article/details/8458101)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Python对象序列化](https://blog.csdn.net/weixin_55696561/article/details/123633077)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值