How to read str from binary file in Python
When you have a file-like object in Python, .read()
will always return bytes
. You can use any of the following solutions to get a str
from the binary file.
Option 1: Decode the bytes
You can call .decode()
on the bytes
. Ensure to use the right encoding. utf-8
is often correct if you don’t know what the encoding is, but
binary = myfile.read() # type: bytes
text = binary.decode("utf-8")
# Short version
text = myfile.read().decode("utf-8")
Option 2: Wrap the file so it appears like a file in text mode
Use io.TextIOWrapper
like this:
import io
text_file = io.TextIOWrapper(myfile, encoding="utf-8")
text = text_file.read()