How can I write 1 byte to a binary file in python
<p>I've tried everything to write just one byte to a file in python. </p>

<pre><code>i=10
fh.write( six.int2byte(i) )
</code></pre>

<p>will output '0x00 0x0a'</p>

<pre><code>fh.write( struct.pack('i', i) )
</code></pre>

<p>will output '0x00 0x0a 0x00 0x00'</p>

<p>I can't understand why this is so hard to do.</p>

<p><code>struct.pack("=b",i)</code> (signed) and <code>struct.pack("=B",i)</code> (unsigned) pack an integer as a single byte which you can see in the <a href="https://docs.python.org/3/library/struct.html#format-characters" rel="nofollow">docs for struct</a>. (<code>"="</code> is for using standard size and ignoring alignment - just in case) so you can do</p>

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

python filehandle writing