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

Glenio
  • 122
  • 8
  • 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? – GregHNZ Mar 22 '20 at 05: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. – Glenio Mar 22 '20 at 05:27

1 Answers1

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?

shantanu pathak
  • 2,018
  • 19
  • 26