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

新手上路,请多包涵

我有一个文件,路径如下:D:/bar/クレイジー・ヒッツ!/foo.abc

我正在解析来自 XML 文件的路径并将其存储在名为 path 的变量中,格式为 file://localhost/D:/bar/クレイジー・ヒッツ!/foo.abc 然后,正在执行以下操作:

 path=path.strip()
path=path[17:] #to remove the file://localhost/  part
path=urllib.url2pathname(path)
path=urllib.unquote(path)

错误是:

 IOError: [Errno 2] No such file or directory: 'D:\\bar\\\xe3\x82\xaf\xe3\x83\xac\xe3\x82\xa4\xe3\x82\xb8\xe3\x83\xbc\xe3\x83\xbb\xe3\x83\x92\xe3\x83\x83\xe3\x83\x84\xef\xbc\x81\\foo.abc'

我在 Windows 7 上使用 Python 2.7

原文由 bcosynot 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 849
2 个回答

你的错误路径是:

 '\xe3\x82\xaf\xe3\x83\xac\xe3\x82\xa4\xe3\x82\xb8\xe3\x83\xbc\xe3\x83\xbb\xe3\x83\x92\xe3\x83\x83\xe3\x83\x84\xef\xbc\x81'

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

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

 >>> a = '\xe3\x82\xaf\xe3\x83\xac\xe3\x82\xa4\xe3\x82\xb8\xe3\x83\xbc\xe3\x83\xbb\xe3\x83\x92\xe3\x83\x83\xe3\x83\x84\xef\xbc\x81'
>>> os.listdir('.')
['?????\xb7???!']
>>> os.listdir(u'.') # Pass unicode to have unicode returned to you
[u'\u30af\u30ec\u30a4\u30b8\u30fc\u30fb\u30d2\u30c3\u30c4\uff01']
>>>
>>> a.decode('utf8') # UTF8 decoding your string matches the listdir output
u'\u30af\u30ec\u30a4\u30b8\u30fc\u30fb\u30d2\u30c3\u30c4\uff01'
>>> os.listdir(a.decode('utf8'))
[u'abc.txt']

所以看来邓肯的建议 path.decode('utf8') 可以解决问题。


更新

我无法为您测试这个,但我建议您在执行 .decode('utf8') 之前尝试检查路径是否包含非 ascii。这有点hacky …

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

原文由 MattH 发布,翻译遵循 CC BY-SA 3.0 许可协议

将文件名作为 unicode 字符串提供给 open 调用。

你如何产生文件名?

如果您将其作为常量提供

在脚本开头附近添加一行:

 # -*- coding: utf8 -*-

然后,在支持 UTF-8 的编辑器中,将 path 设置为 unicode 文件名:

 path = u"D:/bar/クレイジー・ヒッツ!/foo.abc"

从目录内容列表中读取

使用 unicode dirspec 检索目录的内容:

 dir_files= os.listdir(u'.')

从文本文件中读取

使用 codecs.open 打开包含文件名的文件,从中读取 unicode 数据。您需要指定文件的编码(因为您知道计算机上非 Unicode 应用程序的“默认 Windows 字符集”是什么)。

任何状况之下

做一个:

 path= path.decode("utf8")

打开文件之前;如果不是“utf8”,请替换为正确的编码。

原文由 tzot 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题