简体   繁体   中英

How to convert any object to a byte array and keep it on memory?

I'm trying to build a simple convertor for any object to byte array in Python. I took a look on pickle but it only works creating a file and this is not what I need. I also checked json.dump but some objects need a serializer to be dumped.

I need a convertor that keeps my object in memory and can convert any object to byte array.

I'm adding this as an actual answer since it seemed to address your needs. Your use of pickle.dump is the problem since it is designed to take the serialized object and write it to a file (though as pointed out in other answers, it doesn't necessarily have to, but that's beside the point).

The function you want to be using is pickle.dumps , which returns the serialized object directly as a byte array:

someobject = 123
bytes = pickle.dumps(someobject)

The file parameter to Pickler just needs to have a write(b) method that receives the bytes. In principle you can write your own class with your method write(self,b) that does whatever you want with those bites and pass an object of that class to Pickler

Example:

import pickle

class File:
  def write(self,b):
    print(b)

f = File()
p = pickle.Pickler(f)

object = 3.14
p.dump(object)

Output: b'\x80\x03G@\t\x1e\xb8Q\xeb\x85\x1f.'

Instead of printing the bytes, like in this example, you could append them in a list , or anything else you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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