Pickle.dump to variable

后端 未结 2 2006
盖世英雄少女心
盖世英雄少女心 2020-12-07 02:20

I\'m new in python and i wanted to know if there is a solution for this problem:

I know that this may sound strange but i want to save the pickle.dump data into a va

相关标签:
2条回答
  • 2020-12-07 03:05

    Here are the code snippets using pickle.dump() in case you need:

    Dumping from pickle_obj to bytes/string variable

    bytes_output = BytesIO()
    pickle.dump(pickle_obj, model_bytes)
    bytes_output_base64 = base64.b64encode(model_bytes.getvalue()).decode() # convert the bytes to base64 string
    bytes_output.close()
    

    Loading from a base64 string in pickle_data to pickle_obj

    pickle_bytes = BytesIO(base64.b64decode(pickle_data))
    pickle_obj = pickle.loads(pickle_bytes.read())
    pickle_bytes.close()
    

    Hope it helps!

    0 讨论(0)
  • 2020-12-07 03:18

    You are looking for an in-memory file object; in Python 2 that's cStringIO.StringIO(), for Python 3 io.BytesIO(); these act just like file objects and you can have pickle.dump() write to these.

    However, the easier path would be to use pickle.dumps() to dump straight to a string object instead.

    Under the hood, what pickle.dumps() does for you is create an in-memory file object, write the pickle data to it and retrieve the string result for you; see the source code:

    def _dumps(obj, protocol=None, *, fix_imports=True):
        f = io.BytesIO()
        _Pickler(f, protocol, fix_imports=fix_imports).dump(obj)
        res = f.getvalue()
        assert isinstance(res, bytes_types)
        return res
    

    but this way you don't have to do that extra work yourself.

    0 讨论(0)
提交回复
热议问题