Python write string of bytes to file

后端 未结 3 1846
小蘑菇
小蘑菇 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:45

    In Python 3.X, bytes() will turn an integer sequence into a bytes sequence:

    >>> bytes([1,65,2,255])
    b'\x01A\x02\xff'
    

    A generator expression can be used to convert your sequence into integers (note that int(x,0) converts a string to an integer according to its prefix. 0x selects hex):

    >>> list(int(x,0) for x in ['0x28','0x0','0x0','0x0'])
    [40, 0, 0, 0]
    

    Combining them:

    >>> bytes(int(x,0) for x in ['0x28','0x0','0x0','0x0'])
    b'(\x00\x00\x00'
    

    And writing them out:

    >>> L = ['0x28','0x0','0x0','0x0']
    >>> with open('out.dat','wb') as f:
    ...  f.write(bytes(int(x,0) for x in L))
    ...
    4
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-03 23:51
    b=b'\xac\xed\x00\x05sr\x00\x0emytest.ksiazka\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x03L\x00\x05autort\x00\x12Ljava/lang/String;L\x00\x03rokt\x00\x13Ljava/lang/Integer;L\x00\x05tytulq\x00~\x00\x01xpt\x00\x04testpp'
    

    bytes as above how to write to file as string. i want as print show in the file

    0 讨论(0)
提交回复
热议问题