Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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_Python 2.7_Character Encoding - Fatal编程技术网

Python-列出目录时出现UnicodeDecodeError

Python-列出目录时出现UnicodeDecodeError,python,python-2.7,character-encoding,Python,Python 2.7,Character Encoding,我试图在Python2.7中构建一个目录中所有文件的列表,但不管我做什么,最终都会出现UnicodeDecodeError 我的代码是: dirList=os.listdir(目录) 我最终会出现以下错误: UnicodeDecodeError:“ascii”编解码器无法解码位置12处的字节0xc3:序号不在范围内(128) 当条目中包含非ascii字符时,总是引发异常。它通常死在的词尾是“Elavhõbe”。当我用print entry打印它时,它会显示Elavhobe(注意更改的“o”) 奇

我试图在Python2.7中构建一个目录中所有文件的列表,但不管我做什么,最终都会出现UnicodeDecodeError

我的代码是: dirList=os.listdir(目录)

我最终会出现以下错误: UnicodeDecodeError:“ascii”编解码器无法解码位置12处的字节0xc3:序号不在范围内(128)

条目
中包含非ascii字符时,总是引发异常。它通常死在的词尾是“Elavhõbe”。当我用
print entry
打印它时,它会显示Elavhobe(注意更改的“o”)

奇怪的是,每当我尝试通过SSH连接时,我都可以将它们与
directory+'/'+entry
放在一起,而且我从未遇到异常


我的最终目标是构建一个完整的目录路径,并将其传递给
os.path.isdir(fullPath)

好的,我终于找到了解决办法。因为我对python不是很在行,所以我不确定它到底是如何工作的,只是它确实如此

我在文件的顶部添加了以下内容:

import sys

#reload sys and set the default encoding to utf-8
#this will avoid errors when running as host server on server startup
reload(sys)
sys.setdefaultencoding('utf-8')
然后我将我的条目编码为ascii,如下所示:

entry = entry.encode('ascii', 'ignore')
然后一切都很好。希望有一天这能帮助别人

entry = entry.encode('ascii', 'ignore')