Write a binary integer or string to a file in python

前端 未结 5 1821
梦毁少年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:12

    I want that pattern of ones and zeros to be written to a file.

    If you mean you want to write a bitstream from a string to a file, you'll need something like this...

    from cStringIO import StringIO
    
    s = "001011010110000010010"
    sio = StringIO(s)
    
    f = open('outfile', 'wb')
    
    while 1:
        # Grab the next 8 bits
        b = sio.read(8)
    
        # Bail if we hit EOF
        if not b:
            break
    
        # If we got fewer than 8 bits, pad with zeroes on the right
        if len(b) < 8:
            b = b + '0' * (8 - len(b))
    
        # Convert to int
        i = int(b, 2)
    
        # Convert to char
        c = chr(i)
    
        # Write
        f.write(c)
    
    f.close()
    

    ...for which xxd -b outfile shows...

    0000000: 00101101 01100000 10010000                             -`.
    

提交回复
热议问题