Python 序列化 - 为什么选择pickle? [英] Python serialization - Why pickle?

查看:24
本文介绍了Python 序列化 - 为什么选择pickle?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 Python 酸洗是一种以尊重对象编程的方式存储"Python 对象的方法 - 不同于以 txt 文件或 DB 编写的输出.

I understood that Python pickling is a way to 'store' a Python Object in a way that does respect Object programming - different from an output written in txt file or DB.

您是否有关于以下几点的更多详细信息或参考资料:

Do you have more details or references on the following points:

  • 腌制对象存储"在哪里?
  • 为什么酸洗保留的对象表示比存储在数据库中更重要?
  • 我可以将腌制的对象从一个 Python shell 会话检索到另一个吗?
  • 当序列化有用时,您是否有重要的例子?
  • 使用pickle 进行序列化是否意味着数据压缩"?

换句话说,我正在寻找关于酸洗的文档 - Python.doc 解释了如何实现酸洗,但似乎没有深入了解序列化的使用和必要性.

In other words, I am looking for a doc on pickling - Python.doc explains how to implement pickle but seems not dive into details about use and necessity of serialization.

推荐答案

Pickling 是一种将 Python 对象(列表、字典等)转换为字符流的方法.这个想法是这个字符流包含在另一个 python 脚本中重建对象所需的所有信息.

Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script.

至于腌制信息的存储位置,通常会这样做:

As for where the pickled information is stored, usually one would do:

with open('filename', 'wb') as f:
    var = {1 : 'a' , 2 : 'b'}
    pickle.dump(var, f)

这会将我们的 var dict 的腌制版本存储在 'filename' 文件中.然后,在另一个脚本中,您可以从此文件加载到变量中,然后重新创建字典:

That would store the pickled version of our var dict in the 'filename' file. Then, in another script, you could load from this file into a variable and the dictionary would be recreated:

with open('filename','rb') as f:
    var = pickle.load(f)

酸洗的另一个用途是,如果您需要通过网络(可能使用套接字或其他方式)传输此字典.首先需要将其转换为字符流,然后才能通过套接字连接发送.

Another use for pickling is if you need to transmit this dictionary over a network (perhaps with sockets or something.) You first need to convert it into a character stream, then you can send it over a socket connection.

此外,这里没有压缩"可言……这只是一种从一种表示(在 RAM 中)转换为另一种(在文本"中)的方式.

Also, there is no "compression" to speak of here...it's just a way to convert from one representation (in RAM) to another (in "text").

About.com 在这里有一个很好的酸洗介绍.

About.com has a nice introduction of pickling here.

这篇关于Python 序列化 - 为什么选择pickle?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆