Skip to content Skip to sidebar Skip to footer

How To Write 1 Byte To A Binary File?

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' fh.write( struct.pack('i', i) ) will output '0x00 0x

Solution 1:

You can just build a bytes object with that value:

withopen('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.

Solution 2:

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=10withopen('binfile', 'wb') as f:
    f.write(struct.pack("=B",i))

Solution 3:

i=10
f=open('binfile', 'w', encoding='utf-8')
f.write(chr(i))
f.close()

Post a Comment for "How To Write 1 Byte To A Binary File?"