【问题标题】:Reading bytes from file without specifying encoding in Python 3从文件中读取字节而不在 Python 3 中指定编码
【发布时间】:2015-05-27 23:11:46
【问题描述】:

在 Python 2 中,以下内容将愉快地从二进制文件中加载前两个字节:

with open(file_name) as f:
    b = f.read(2)

但是,在 Python 3 中,同样可能会导致例如:

UnicodeDecodeError: 'utf-8' codec can't decode byte 2: invalid start byte

这让我想到了一个问题:如何在 Python 3 中在不指定编码的情况下从文件中读取 N 个原始字节?

【问题讨论】:

    标签: python file python-3.x encoding python-2.x


    【解决方案1】:

    指定二进制模式:

    with open(file_name, 'rb') as f:
    

    您也应该在 Python 2 中这样做,除非您希望 CRLF 之类的错误成为二进制文件中的 LF。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多