How to write 1 byte to a binary file?

前端 未结 2 1597
小蘑菇
小蘑菇 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:00

    struct.pack("=b",i) (signed) and struct.pack("=B",i) (unsigned) pack an integer as a single byte which you can see in the docs for struct. ("=" is for using standard size and ignoring alignment - just in case) so you can do

    import struct
    i=10
    with open('binfile', 'wb') as f:
        f.write(struct.pack("=B",i))
    

提交回复
热议问题