在Windows上的Python 2中打开名称中带有重音符号的文件 [英] opening a file with an accented character in its name, in Python 2 on Windows
问题描述
在Windows的目录中,我有2个文件,两个文件的名称均带有重音符号:t1û.fn
和t2ű.fn
;命令提示符中的dir
命令正确显示了两者:
In a directory in Windows I have 2 files, both of them with an accented character in its name: t1û.fn
and t2ű.fn
; The dir
command in the Command Prompt shows both correctly:
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无法同时看到两个文件:
However, Python can't see both files:
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
.
It looks like Python 2 uses a single-byte API for filenames, thus the accented character in t1û.fn is mapped to the single byte \xfb
, and the accented character in t2ű.fn is mapped to the unaccented ASCII single byte u
.
在Windows 2中,如何在Windows上对文件名使用多字节API?我想在Windows的Python 2控制台版本中打开这两个文件.
How is it possible to use a multi-byte API for filenames on Windows in Python 2? I want to open both files in the console version of Python 2 on Windows.
推荐答案
使用unicode字符串:
Use a unicode string:
f1 = open(u"t1\u00fb.fn") # t1û.fn
f2 = open(u"t2\u0171.fn") # t2ű.fn
这篇关于在Windows上的Python 2中打开名称中带有重音符号的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!