栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python无法打开路径中包含非英语字符的文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python无法打开路径中包含非英语字符的文件

您的错误路径为:

'xe3x82xafxe3x83xacxe3x82xa4xe3x82xb8xe3x83xbcxe3x83xbbxe3x83x92xe3x83x83xe3x83x84xefxbcx81'

我认为这是文件名的UTF8编码版本。

我在Windows7上创建了一个同名文件夹,并在其中放置了一个名为“ abc.txt”的文件:

>>> a = 'xe3x82xafxe3x83xacxe3x82xa4xe3x82xb8xe3x83xbcxe3x83xbbxe3x83x92xe3x83x83xe3x83x84xefxbcx81'>>> os.listdir('.')['?????xb7???!']>>> os.listdir(u'.') # Pass unipre to have unipre returned to you[u'u30afu30ecu30a4u30b8u30fcu30fbu30d2u30c3u30c4uff01']>>> >>> a.depre('utf8') # UTF8 decoding your string matches the listdir outputu'u30afu30ecu30a4u30b8u30fcu30fbu30d2u30c3u30c4uff01'>>> os.listdir(a.depre('utf8'))[u'abc.txt']

因此,邓肯的建议似乎可以解决问题

path.depre('utf8')


更新资料

我无法为您进行测试,但是建议您在执行之前尝试检查路径是否包含非ascii

.depre('utf8')
。这有点hacky …

ASCII_TRANS = '_'*32 + ''.join([chr(x) for x in range(32,126)]) + '_'*130path=path.strip()path=path[17:] #to remove the file://localhost/  partpath=urllib.unquote(path)if path.translate(ASCII_TRANS) != path: # Contains non-ascii  path = path.depre('utf8')path=urllib.url2pathname(path)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/624526.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号