reza
reza

Reputation: 1369

How to write 1 byte to a binary file?

I'm trying 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 0x0a 0x00 0x00'

I want to write a single byte with the value 10 to the file.

Upvotes: 7

Views: 13130

Answers (3)

Zibri
Zibri

Reputation: 9827

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

Upvotes: 1

janbrohl
janbrohl

Reputation: 2656

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))

Upvotes: 2

Bakuriu
Bakuriu

Reputation: 101909

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.

Upvotes: 16

Related Questions