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>You can just build a <code>bytes</code> object with that value:</p>

<pre><code>with open('my_file', 'wb') as f:
    f.write(bytes([10]))
</code></pre>

<p>This works only in python3. If you replace <code>bytes</code> with <code>bytearray</code> it works in both python2 and 3.</p>

<p>Also: remember to open the file in binary mode to write bytes to it.</p>

python filehandle writing