Write to file bytes and strings
<p>I have to create files which have some chars and hex value in little-endian encoding. To do encoding, I use:</p>

<pre><code>pack("I", 0x01ddf23a)
</code></pre>

<p>and this give me:</p>

<pre><code>b':\xf2\xdd\x01'
</code></pre>

<p>First problem is that, this give me bytes string which I cannot write to file. Second one is that \x3a is turn to ':'. What I expect, is write to file \x3a\xf2\xdd\x01 as bytes not as chars.</p>

<p>What I tried:</p>

<pre><code>&gt;&gt;&gt; a=0x01ddf23a

&gt;&gt;&gt; str(pack("I", a))
"b':\\xf2\\xdd\\x01'" &lt;= wrong

&gt;&gt;&gt; pack("I", a).hex()
'3af2dd01             &lt;= I need '\x' before each byte

&gt;&gt;&gt; pack("I", a).decode()
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in &lt;module&gt;
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf2 in position 1: invalid continuation byte
</code></pre>

<p>Changing open() from "w" to "wb" force me to write only bytes, but I want to writes lots of strings and few bytes, eg.:</p>

<pre><code>Hello world
^I^M^T^B
End file
</code></pre>

<p>I know I can simple do this:</p>

<pre><code>fs.open("file" "w")
fs.write("Hello world")
fs.write("\x3a\xf2\xdd\x01")
fs.write("End file")
fs.close()
</code></pre>

<p>But this is make my byte value 0x01ddf23a hard to read and there is easy to make some mistake when changing this value in that form.</p>

<p>You are producing bytes, which can be written to files opened in <em>binary mode</em> without issue. Add <code>b</code> to the file mode when opening and either use <code>bytes</code> string literals or encode your strings to bytes if you need to write other data too:</p>

<pre><code>with open("file", "wb") as fs:
    fs.write(b"Hello world")  # note, a byte literal!
    fs.write(pack("I", 0x01ddf23a))
    fs.write("End file".encode('ASCII'))  # encoded string to bytes
</code></pre>

<p>The alternative would be to decode your binary packed data to a text string first, but since packed data does not, in fact, contain decodable text, that approach would require contortions to <em>force</em> the binary data to be decodable and encodable again, which only works if your file encoding was set to Latin-1 and severely limits what actual text you could add.</p>

<p>A <code>bytes</code> representation will always try to show <em>printable characters</em> where possible. The byte <code>\x3a</code> is also the correct ASCII value for the <code>':'</code> character, so in a <code>bytes</code> representation the latter is preferred over using the <code>\x3a</code> escape sequence. The <em>correct value</em> is present in the <code>bytes</code> value and would be written to the file entirely correctly:</p>

<pre><code>&gt;&gt;&gt; b'\x3a'
b':'
&gt;&gt;&gt; b'\x3a' == b':'
True
&gt;&gt;&gt; b':'[0]
58
&gt;&gt;&gt; b'\x3a'[0]
58
&gt;&gt;&gt; hex(58)
'0x3a'
</code></pre>

python python-3.x file-io byte