user3075816
user3075816

Reputation: 169

How to write/pack a binary string to file in Python

I would like to do a simple operations, but I'm not able to manage it. I have a string of '0' and '1' derived by a coding algorithm. I would like to write it to file but I think that I'm doing wrongly.

My string is something like '11101010000......10000101010'

Actually I'm writing a binary file as:

print 'WRITE TO FILE '
with open('file.bin', 'wb') as f:
    f.write(my_coded_string)

print 'READ FROM FILE' 
with open('file.bin', 'rb') as f:
    myArr = bytearray(f.read())
myArr = str(myArr)

If I look at the size of the file, I get something pretty big. So I guess that I'm using an entire byte to write each 1 and 0. Is that correct?

I have found some example which use the 'struct' function but I didn't manage to understand how it works.

Thanks!

Upvotes: 2

Views: 2559

Answers (2)

Mohammad Mohagheghi
Mohammad Mohagheghi

Reputation: 41

Because input binary is string python writes each bit as a char. You can write your bit streams with bitarray module from

like this:

from bitarray import bitarray

str = '110010111010001110'

a = bitarray(str)
with open('file.bin', 'wb') as f:
    a.tofile(f)

b = bitarray()    
with open('file.bin', 'rb') as f:
    b.fromfile(f)

print b

Upvotes: 4

Marek Nowaczyk
Marek Nowaczyk

Reputation: 257

Use this:

import re
text = "01010101010000111100100101"
bytes = [ chr(int(sbyte,2)) for sbyte in re.findall('.{8}?', text) ]

to obtain a list of bytes, that can be append to binary file, with

with open('output.bin','wb') as f:
    f.write("".join(bytes))

Upvotes: 2

Related Questions