【问题标题】:opening a file with an accented character in its name, in Python 2 on Windows在 Windows 上的 Python 2 中打开名称中带有重音字符的文件
【发布时间】:2018-02-12 00:06:24
【问题描述】:

在 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 控制台版本中打开这两个文件。

【问题讨论】:

  • 仅供参考,如果您跳转到 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


【解决方案1】:

使用 unicode 字符串:

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

【讨论】:

  • 谢谢,它适用于open。同样os.listdir(u'.') 返回带有右重音字符的文件名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 2016-06-16
  • 2015-07-01
  • 1970-01-01
  • 2018-10-30
相关资源
最近更新 更多