Windows下的Python中的文件名格式

时间:2011-06-21 13:16:47

标签: python unicode codepages mbcs

我有两个名为的文件:

  

'╠.txt'和'| .txt'

这么简单的代码:

files = os.listdir('E:\pub\private\desktop\')
for f in files:
    print f, repr(f), type (f)

会返回

¦.txt '\xa6.txt' <type 'str'>
¦.txt '\xa6.txt' <type 'str'>

我不明白为什么我为╠字符而不是OxCC获取代码0xA6。 我一直试图用编码解码方法来玩arround,但没有成功。 我注意到sys.getfilesystemencoding()设置为mbcs - 但是我无法像cp437那样改变它。

非常感谢任何帮助。 谢谢!

1 个答案:

答案 0 :(得分:4)

你必须将一个unicode字符串传递给os.listdir,Python将返回unicode文件名:

# a string that is unicode+raw (escapes \)
path = ur"E:\pub\private\desktop"
print os.listdir(path)
# [u'\xa6.txt', u'\u2560.txt']

Windows NT实际上使用unicode作为文件名,但我猜Python在传递编码路径名时会尝试对它们进行编码。