Python序列化-为什么要泡菜? [英] Python serialization - Why pickle?

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

问题描述

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

您在以下几点上有更多详细信息或参考吗?

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

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

解决方案

腌制是一种将python对象(列表,字典等)转换为字符流的方法.想法是,此字符流包含在另一个python脚本中重构对象所需的所有信息.

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

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

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

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

腌制的另一种用途是,如果您需要通过网络(可能是通过套接字或其他方式)传输此字典,则首先需要将其转换为字符流,然后可以通过套接字连接进行发送.

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

About.com在此处中对酸洗进行了很好的介绍. /p>

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:

  • where are pickled objects 'stored'?
  • why is pickling preserving object representation more than, say, storing in DB?
  • can I retrieve pickled objects from one Python shell session to another?
  • do you have significant examples when serialization is useful?
  • does serialization with pickle imply data 'compression'?

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 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)

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.

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 has a nice introduction of pickling here.

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

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