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

bco*_*not 10 python file path url-encoding

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

我正在从XML文件解析路径并将其存储在以 Then 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)
Run Code Online (Sandbox Code Playgroud)

错误是:

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'
Run Code Online (Sandbox Code Playgroud)

更新1:我在Windows 7上使用Python 2.7

Mat*_*ttH 5

您的错误路径是:

'\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'
Run Code Online (Sandbox Code Playgroud)

我认为这是文件名的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']
Run Code Online (Sandbox Code Playgroud)

因此,邓肯的建议似乎可以解决问题path.decode('utf8')


更新资料

我无法为您进行测试,但是建议您在执行之前尝试检查路径是否包含非ascii .decode('utf8')。这有点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)
Run Code Online (Sandbox Code Playgroud)