How to write 1 byte to a binary file?

江枫思渺然 提交于 2019-12-01 00:26:44

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.

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))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!