1

Let's say I have two bytearray,

b = bytearray(b'aaaaaa')
b1 = bytearray(b'bbbbbb')
file_out = open('bytes.bin', 'ab')
file_out.write(b)
file_out.write(b1)

this code will create a .bin file which contains two bytearrays

how to read this file and store those two variables also decode them back to string?

my goal is to transfer these bytes for other programs to read by making a file. I'm not sure if this bytearray + appending is a good idea.

Thanks

2
  • The trick will be when reading the file to figure out where b ends and b1 starts. Also using 'ab' when you open it, does that mean that the second time you run this code it will add it to the end? Commented Mar 22, 2020 at 5:15
  • @GregHNZ exactly, the second time I run this code it will add it to the end. I'm guessing in when the bytes.bin is read and converted as a string it will show b'0x\31\......' you are right about figure out where b end and b1 starts. My idea is by using bytes delimter, however i can't see the point of using the bytearray. Commented Mar 22, 2020 at 5:27

1 Answer 1

1

Pythons pickle is meant for storing and retrieving objects.

It will take care of encoding and decoding of the contents.

You can use it in your case like following,

import pickle

b = bytearray(b'aaaaaa')
b1 = bytearray(b'bbbbbb')

# Saving the objects:
with open('objs.pkl', 'wb') as f:  
    pickle.dump([b, b1], f)

# Getting back the objects:
with open('objs.pkl') as f:  
    b, b1 = pickle.load(f)

You can find more details from other question How do I save and restore multiple variables in python?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.