Write a binary integer or string to a file in python

前端 未结 5 1818
梦毁少年i
梦毁少年i 2020-12-16 00:46

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

5条回答
  •  失恋的感觉
    2020-12-16 01:14

    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'
    

提交回复
热议问题