在 Python 中包装二进制类文件对象以获取解码的文本类文件对象

问题:

在 Python 中,你有一个读取二进制数据的类文件对象(例如如果你使用 open("my-file", "rb") 打开文件)

你想将该类文件对象传递给一个期望文本模式下类文件对象(即可以从中读取 str 而不是 bytes)的函数。

解决方案

使用 io.TextIOWrapper

textiowrapper_example.py
with open("fp-lib-table", "rb") as infile:
    # infile.read() 将返回 bytes
    text_infile = io.TextIOWrapper(infile)
    # text-infile.read() 将返回 str

如果你需要使用特定编码,使用 encoding=...

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

Check out similar posts by category: Python