Python write string of bytes to file

后端 未结 3 1848
小蘑菇
小蘑菇 2021-01-03 23:20

How do I write a string of bytes to a file, in byte mode, using python?

I have:

[\'0x28\', \'0x0\', \'0x0\', \'0x0\']

How do I writ

3条回答
  •  鱼传尺愫
    2021-01-03 23:47

    Map to a bytearray() or bytes() object, then write that to the file:

    with open(outputfilename, 'wb') as output:
        output.write(bytearray(int(i, 16) for i in yoursequence))
    

    Another option is to use the binascii.unhexlify() function to turn your hex strings into a bytes value:

    from binascii import unhexlify
    
    with open(outputfilename, 'wb') as output:
        output.write(unhexlify(''.join(format(i[2:], '>02s') for i in b)))
    

    Here we have to chop off the 0x part first, then reformat the value to pad it with zeros and join the whole into one string.

提交回复
热议问题