Python写入/读取1 0字符串到二进制文件

时间:2019-11-20 06:28:59

标签: binary byte python-3.6

我正在尝试将字符串1的0写入/读取到实际的二进制文件中,但是在读取时遇到了一些麻烦。我写的时候的字节数组是bytearray(b'\ xcc \ xcc \ x9c \ xe79 \ xadkZ \ xd6 \ x0b'),但是当我读取每个字节时,它显示很奇怪。输出是这样的

b'\x9c'
b'\xe7'
b'9'
b'\xad'
b'k'
b'Z'
....

这是我的代码

def writefile():
    longstring = "1100110011001100100111001110011100111001101011010110101101011010110101101011"

    with open('file', 'wb') as f:
        bit_strings = [longstring[i:i + 8] for i in range(0, len(longstring), 8)]
        byte_list = [int(b, 2) for b in bit_strings]
        print(bytearray(byte_list))
        f.write(bytearray(byte_list))
        f.close()

def readfile():
    longbin = ""
    with open('file', 'rb') as f:
        #print(f.readline())
        byte = f.read(1)
        while byte != b"":
            print(byte)
            #longbin = longbin + '{0:08b}'.format(ord(byte))
            byte = f.read(1)
    print(longbin)

0 个答案:

没有答案