Python: a string of 1s and 0s & # 8594; binary file

I have a string of 1 and 0 in Python, and I would like to write it to a binary file. I have a lot of trouble finding a good way to do this.

Is there a standard way to do this that I'm just missing?

+4
source share
5 answers

If you need a binary file,

>>> import struct >>> myFile=open('binaryFoo','wb') >>> myStr='10010101110010101' >>> x=int(myStr,2) >>> x 76693 >>> struct.pack('i',x) '\x95+\x01\x00' >>> myFile.write(struct.pack('i',x)) >>> myFile.close() >>> quit() 
 $ cat binaryFoo  +$ 

Is this what you are looking for?

+8
source
 In [1]: int('10011001',2) Out[1]: 153 

Divide your input into pieces of eight bits, then apply int(_, 2) and chr , then concatenate into a line and write that line to a file.

Sort of...:

 your_file.write(''.join(chr(int(your_input[8*k:8*k+8], 2)) for k in xrange(len(your_input)/8))) 
+2
source
 BITS_IN_BYTE = 8 chars = '00111110' bytes = bytearray(int(chars[i:i+BITS_IN_BYTE], 2) for i in xrange(0, len(chars), BITS_IN_BYTE)) open('filename', 'wb').write(bytes) 
0
source

Or you can use an array module like this

 $ python Python 2.7.2+ (default, Oct 4 2011, 20:06:09) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import random,array #This is the best way, I could think of for coming up with an binary string of 100000 >>> binStr=''.join([str(random.randrange(0,2)) for i in range(100000)]) >>> len(binStr) 100000 >>> a = array.array("c", binStr) #c is the type of data (character) >>> with open("binaryFoo", "ab") as f: ... a.tofile(f) ... #raw writing to file >>> quit() $ 
0
source

Now there is a bitstring module that does what you need.

 from bitstring import BitArray my_str = '001001111' binary_file = open('file.bin', 'wb') b = BitArray(bin=my_str) b.tofile(binary_file) binary_file.close() 

You can test it from a shell on Linux with xxd -b file.bin

0
source

All Articles