Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.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.x 存在BOM时检测Python3中的编码_Python 3.x - Fatal编程技术网

Python 3.x 存在BOM时检测Python3中的编码

Python 3.x 存在BOM时检测Python3中的编码,python-3.x,Python 3.x,首先,我知道你不能总是检测编码,这不是问题的目的。当打开一个文件时,Python能检测到编码吗?当有一个给出编码的BOM表时 我有一套档案。有些是UTF-16(所以他们有一个BOM这样说),有些是拉丁语1。让我们忽略拉丁-1文件的边缘大小写,由于某些原因,这些文件的开头字符与UTF-16 BOM完全相同。我想在打开文件时查找BOM表。如果有,请使用与BOM表关联的编码自动打开文件。如果没有BOM表,请使用拉丁语1打开 以下是我的解决方法: with open(filename,mode=&quo

首先,我知道你不能总是检测编码,这不是问题的目的。当打开一个文件时,Python能检测到编码吗?当有一个给出编码的BOM表时

我有一套档案。有些是UTF-16(所以他们有一个BOM这样说),有些是拉丁语1。让我们忽略拉丁-1文件的边缘大小写,由于某些原因,这些文件的开头字符与UTF-16 BOM完全相同。我想在打开文件时查找BOM表。如果有,请使用与BOM表关联的编码自动打开文件。如果没有BOM表,请使用拉丁语1打开

以下是我的解决方法:

with open(filename,mode="rb") as f:
    text=f.readlines()
    text=b''.join(text)
    if text[:2]==(b'\xff\xfe'):
        text=text.decode("utf-16")
    else:
        text=text.decode("iso-8859-1")
是否有某种模块可以用具有BOM表的所有编码替换“open”来实现这一点