简体   繁体   English

使用协议选项的cPickle文件

[英]cPickle file using protocol option

I have silly question. 我有一个愚蠢的问题。 Is possible to re-pickle(cPickle) an already cPickled file using another protocol option, and also which protocol would be best for a very large file. 可以使用另一个协议选项重新整理(cPickle)已经cPickled的文件,以及哪种协议最适合非常大的文件。 Would appreciate any help/suggestions. 不胜感激任何帮助/建议。

I don't really understand what you mean by pickling a file. 我真的不明白您腌制文件的意思。 Do you want to read a pickled file as binary without unpickling and then pickle it again? 您是否要在不取消腌制的情况下将腌制的文件读取为二进制文件,然后再次对其进行腌制? This should not be a problem but I do not see what good it would do... 这应该不成问题,但我不知道它将有什么好处...

The default protocol version in pickle is 0, ASCII ( pickle docs ). pickle的默认协议版本为0,ASCII( pickle docs )。 The latest binary protocol is 2, which gives you smaller file sizes. 最新的二进制协议是2,这使您的文件更小。 For me a binary pickle output was only half as big for som jpg picture as with an ASCII pickle, code below. 对我来说,som jpg图片的二进制泡菜输出只有ASCII泡菜(以下代码)的一半。

You might want to consider cerealizer which has a pickle like interface but is more secure. 您可能要考虑谷物腌制机 ,其界面类似于泡菜,但更安全。 It seems to have its own binary protocol, file size being about as small as with pickle binary. 它似乎有自己的二进制协议,文件大小大约与pickle二进制文件一样小。

import cerealizer
#import cPickle as cerealizer

def save(data, filename):
    f = open(filename,"wb")
    cerealizer.dump(data, f, protocol=2)
    f.close()

def load(filename):
    f = open(filename,"rb")
    p = cerealizer.load(f)
    f.close()
    return(p)

if __name__ == "__main__":
    import PIL.Image
    import cStringIO as StringIO

    stringIO = StringIO.StringIO()
    im = PIL.Image.open("picture.jpg")
    im.save(stringIO, "JPEG")

    stringIO.seek(0)
    save(stringIO.read(), "testCerealizerIm.txt")

    binaryImageData = load("testCerealizerIm.txt")

    stringIO2 = StringIO.StringIO()
    stringIO2.write(binaryImageData)

    stringIO2.seek(0)
    im = PIL.Image.open(stringIO2)
    im.show()

You unpickle it and repickle it. 您拨开并重新拨开它。 The protocol version can be choosen as part of the pickle API: 协议版本可以作为pickle API的一部分进行选择:

http://docs.python.org/library/pickle.html http://docs.python.org/library/pickle.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM