Wrap binary file-like object to get decoded text file-like object in Python


In Python, you have a file-like object that reads binary data (e.g. if you open a file using open("my-file", "rb"))

You want to pass that file-like object to a function that expects a file-like object that expects a file-like object in text mode (i.e. where you can read *str*from, not bytes).


Use io.TextIOWrapper:

with open("fp-lib-table", "rb") as infile:
    # infile.read() would return bytes
    text_infile = io.TextIOWrapper(infile)
    # text-infile.read() would return a str

In case you need to use a specific encoding, use encoding=...:

text_infile = io.TextIOWrapper(infile, encoding="utf-8")