Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python 3中读取文件中的字节而不指定编码_Python_File_Python 3.x_Encoding_Python 2.x - Fatal编程技术网

在Python 3中读取文件中的字节而不指定编码

在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_

在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_name, 'rb') as f:
您也应该在Python 2中这样做,除非您希望CRLFs之类的bug在二进制文件中变成LFs。

指定二进制模式:

with open(file_name, 'rb') as f:
您也应该在Python2中这样做,除非您希望像CRLFs这样的bug在二进制文件中变成LFs