python3读取未知编码文件时无法提前判断其编码,怎样解决

谢邀。多看看文档吧,传个 mode=\u0026#39;rb\u0026#39; 试试:As mentioned in the Overview, Python distinguishes between binary and text I/O. Files opened in binary mode (including \u0026#39;b\u0026#39; in themode argument) return contents as bytes objects without any decoding. In text mode (the default, or when \u0026#39;t\u0026#39; is included in the modeargument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.
■网友
rb拉进来转之(类py2)或者try except到死……编码这坑,逃不过去的……
■网友
import chardect#以txt文件为例,其实其他的也可以secret_encoding_file = \u0026#39;某未知编码文件.txt\u0026#39;#为了减少内存,建议用readline只读第一行数据。而不是read全部读入bytes_data = https://www.zhihu.com/api/v4/questions/46962868/open(secret_encoding_file, /u0026#39;rb/u0026#39;).readline()#返回该字符节数据使用的编码 方式encoding_info = chardect.dectect(bytes_data)#查看编码方式print(encoding_info) 【python3读取未知编码文件时无法提前判断其编码,怎样解决】

■网友
import chardets=open(path,\u0026#39;rb\u0026#39;).read() charset=chardet.detect(s)print(charset)已二进制‘rb’模式读取,然后判断编码

■网友
Open时用\u0026#39;rb\u0026#39;二进制读取就可以了


    推荐阅读