How to write 1 byte to a binary file?

前端 未结 2 1626
小蘑菇
小蘑菇 2021-01-07 04:14

I\'ve tried everything to write just one byte to a file in python.

i = 10
fh.write( six.int2byte(i) )

will output \'0x00 0x0a\'

         


        
2条回答
  •  情书的邮戳
    2021-01-07 05:01

    You can just build a bytes object with that value:

    with open('my_file', 'wb') as f:
        f.write(bytes([10]))
    

    This works only in python3. If you replace bytes with bytearray it works in both python2 and 3.

    Also: remember to open the file in binary mode to write bytes to it.

提交回复
热议问题