代码之家  ›  专栏  ›  技术社区  ›  pts

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

  •  1
  • pts  · 技术社区  · 8 年前

    在Windows的一个目录中,我有两个文件,它们的名称中都有重音字符: 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
    

    screenshot of dir

    但是,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 u

    在Python 2中,如何在Windows上为文件名使用多字节API?我想在Windows上的Python 2控制台版本中打开这两个文件。

    1 回复  |  直到 8 年前
        1
  •  2
  •   selbie    8 年前

    使用unicode字符串:

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