How to write bytes to a file in Python 3 without knowing the encoding? How to write bytes to a file in Python 3 without knowing the encoding? python-3.x python-3.x

How to write bytes to a file in Python 3 without knowing the encoding?


It's a matter of using APIs that operate on bytes, rather than strings.

sys.stdout.buffer.write(bytes_)

As the docs explain, you can also detach the streams, so they're binary by default.

This accesses the underlying byte buffer.

tempfile.TemporaryFile().write(bytes_)

This is already a byte API.

open('filename', 'wb').write(bytes_)

As you would expect from the 'b', this is a byte API.

from io import BytesIOBytesIO().write(bytes_)

BytesIO is the byte equivalent to StringIO.

EDIT: write will Just Work on any binary file-like object. So the general solution is just to find the right API.


Specify binary mode, 'b', when you open your file:

with open('myfile.txt', 'wb') as w:    w.write(bytes)

https://docs.python.org/3.3/library/functions.html#open