在 Python 2 on Windows 中打开名称中带有重音字符的文件

opening a file with an accented character in its name, in Python 2 on Windows

在 Windows 的目录中,我有 2 个文件,它们的名称中都有一个重音字符:t1û.fnt2ű.fn;命令提示符中的 dir 命令正确显示:

S:\p>dir t*.fn
 Volume in drive S is q
 Volume Serial Number is 05A0-8823

 Directory of S:\p

2017-09-03  14:54                 4 t1û.fn
2017-09-03  14:54                 4 t2ű.fn
               2 File(s)              8 bytes
               0 Dir(s)  19,110,621,184 bytes free

截图:

但是,Python 看不到这两个文件:

S:\p>python -c "import os; print [(fn, os.path.isfile(fn)) for fn in os.listdir('.') if fn.endswith('.fn')]"
[('t1\xfb.fn', True), ('t2u.fn', False)]

看起来 Python 2 使用单字节 API 作为文件名,因此 t1û.fn 中的重音字符映射到单字节 \xfb,并且重音字符t2ű.fn 中的字符映射到无重音的 ASCII 单字节 u.

Python 2 中 Windows 上的文件名如何使用多字节 API?我想在 Windows.

的 Python 2 控制台版本中打开这两个文件

使用 unicode 字符串:

f1 = open(u"t1\u00fb.fn")     # t1û.fn
f2 = open(u"t2\u0171.fn")     # t2ű.fn