在Python 3中读取文件中的字节而不指定编码
在Python 2中,以下内容将从二进制文件加载前两个字节:在Python 3中读取文件中的字节而不指定编码,python,file,python-3.x,encoding,python-2.x,Python,File,Python 3.x,Encoding,Python 2.x,在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个原始字节?指定二进制模式: with open(file_
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个原始字节?指定二进制模式:
with open(file_name, 'rb') as f:
您也应该在Python 2中这样做,除非您希望CRLFs之类的bug在二进制文件中变成LFs。指定二进制模式:
with open(file_name, 'rb') as f:
您也应该在Python2中这样做,除非您希望像CRLFs这样的bug在二进制文件中变成LFs