【发布时间】:2018-02-12 00:06:24
【问题描述】:
在 Windows 的一个目录中,我有 2 个文件,它们的名称中都有一个重音字符:t1û.fn 和 t2ű.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 控制台版本中打开这两个文件。
【问题讨论】:
-
仅供参考,如果您跳转到 Python 3,请注意
bytes路径由于这种行为在 Windows 上已被弃用。通过假装文件系统编码为 UTF-8,支持在 3.6+ 中返回的bytes路径。在 3.6 中,除了"t1û.fn"之外,您还可以打开b't1\xc3\xbb.fn',并且os.listdir(b'.')将文件名编码为 UTF-8。它在内部转码为 UTF-16 以使用 Windows 宽字符 API。
标签: windows unicode filenames python-2.x