2017-09-03 170 views
0

在Windows中的一个目录中,我有两个文件,它们的名称中都带有重音符:t1û.fnt2ű.fn;在命令提示符下键入命令dir同时显示正确:在Windows的Python 2中打开名称中带有重音字符的文件

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,并且acce t2ű.fn中的nted字符映射到无重音的ASCII单字节u

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

+0

仅供参考,如果你做跳跃到Python 3,注意'bytes'路径被抛弃了,因为这种行为在Windows上。通过假装文件系统编码为UTF-8,支持在3.6+中返回的“字节”路径。在3.6中你可以打开'b't1 \ xc3 \ xbb.fn'',''t1û.fn'','os.listdir(b'。')'将文件名编码为UTF-8。它在内部转码为UTF-16以使用Windows宽字符API。 – eryksun

回答

1

使用unicode字符串:

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

谢谢,它适用于'open'。 'os.listdir(u'。')'返回带有正确重音字符的文件名。 – pts

相关问题