如何在 Python 中从二进制文件读取 str
当你在 Python 中有类文件对象时,.read() 将始终返回 bytes。你可以使用以下任何解决方案从二进制文件获取 str。
选项 1:解码 bytes
你可以在 bytes 上调用 .decode()。确保使用正确的编码。如果你不知道编码是什么,utf-8 通常是正确的,但是
decode_bytes_example.py
binary = myfile.read() # type: bytes
text = binary.decode("utf-8")
# 简短版本
text = myfile.read().decode("utf-8")选项 2:包装文件使其看起来像文本模式下的文件
像这样使用 io.TextIOWrapper:
textiowrapper_read_example.py
import io
text_file = io.TextIOWrapper(myfile, encoding="utf-8")
text = text_file.read()Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow