Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.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 尝试打开文件时出现UnicodeDecodeError_Python_Eclipse_Python 3.x - Fatal编程技术网

Python 尝试打开文件时出现UnicodeDecodeError

Python 尝试打开文件时出现UnicodeDecodeError,python,eclipse,python-3.x,Python,Eclipse,Python 3.x,我试图打开一个文件,但不断出现错误(解码错误)。最后,我遇到了一个关于stackoverflow的话题,并且更进一步。然而,现在当我尝试循环浏览我的文件时,我没有得到任何结果。该文件是uTorrent的设置文件。我对Python和编程相当陌生,所以我想我可以尝试从该文件中读取和提取一些参数 getDir = r'{0}/{1}/{2}/AppData/Roaming/uTorrent/settings.dat'.format(partition, "Users", user) data =

我试图打开一个文件,但不断出现错误(解码错误)。最后,我遇到了一个关于stackoverflow的话题,并且更进一步。然而,现在当我尝试循环浏览我的文件时,我没有得到任何结果。该文件是uTorrent的设置文件。我对Python和编程相当陌生,所以我想我可以尝试从该文件中读取和提取一些参数

getDir = r'{0}/{1}/{2}/AppData/Roaming/uTorrent/settings.dat'.format(partition, 
"Users", user)

data = []
try:
    with codecs.open(getDir, "r") as f:
        for lines in f:
            data.append(lines)
except UnicodeEncodeError:
    pass
当我使用Unicode DeencodeError时,我得到一个错误,但其他异常除外。我尝试过使用/不使用codecdes.open,为了在open函数中指定解码类型,我还使用了ignore。代码已通过,但列表仍为空

UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 1962: character maps to <undefined>

真的很感谢你的帮助,谢谢你的网站

摘要

打开文件时需要指定编码。如果编码是“utf-16”,则看起来是这样的,尽管从您给出的示例来看,可能不是这样

with codecs.open(getDir, "r", encoding="utf-16") as f:
错误处理

您还可以通过输入参数“errors”来指定如何处理错误。这允许您替换未知字符或忽略它们。有关更多详细信息,请参见此处:

额外阅读


您可能想知道如何确定编码?总之,您需要被告知编码是什么。这里有一个链接以简明易懂的方式描述编码和解码:

您没有指定目标编码。你知道哪一个是?不,请告诉我我是怎么做到的。
with codecs.open(getDir, "r", encoding="utf-16") as f: