Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a binary integer or string to a file in python

I have a string (it could be an integer too) in Python and I want to write it to a file. It contains only ones and zeros I want that pattern of ones and zeros to be written to a file. I want to write the binary directly because I need to store a lot of data, but only certain values. I see no need to take up the space of using eight bit per value when I only need three.

For instance. Let's say I were to write the binary string "01100010" to a file. If I opened it in a text editor it would say b (01100010 is the ascii code for b). Do not be confused though. I do not want to write ascii codes, the example was just to indicate that I want to directly write bytes to the file.


Clarification:

My string looks something like this:

binary_string = "001011010110000010010"

It is not made of of the binary codes for numbers or characters. It contains data relative only to my program.

like image 869
KFox Avatar asked Jun 02 '13 21:06

KFox


2 Answers

To write out a string you can use the file's .write method. To write an integer, you will need to use the struct module

import struct

#...
with open('file.dat', 'wb') as f:
    if isinstance(value, int):
        f.write(struct.pack('i', value)) # write an int
    elif isinstance(value, str):
        f.write(value) # write a string
    else:
        raise TypeError('Can only write str or int')

However, the representation of int and string are different, you may with to use the bin function instead to turn it into a string of 0s and 1s

>>> bin(7)
'0b111'
>>> bin(7)[2:] #cut off the 0b
'111'

but maybe the best way to handle all these ints is to decide on a fixed width for the binary strings in the file and convert them like so:

>>> x = 7
>>> '{0:032b}'.format(x) #32 character wide binary number with '0' as filler
'00000000000000000000000000000111'
like image 146
Ryan Haining Avatar answered Oct 11 '22 18:10

Ryan Haining


Brief example:

my_number = 1234
with open('myfile', 'wb') as file_handle:
    file_handle.write(struct.pack('i', my_number))
...
with open('myfile', 'rb') as file_handle:
    my_number_back = struct.unpack('i', file_handle.read())[0]
like image 40
ThorSummoner Avatar answered Oct 11 '22 17:10

ThorSummoner