2

我有两个不同的文件,称为:

'╠.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'>

我不明白为什么我得到╠字符的代码 0xA6 而不是 OxCC。我一直在尝试使用编码解码方法,但没有成功。我注意到 sys.getfilesystemencoding() 设置为 mbcs - 但我无法设法将其更改为 cp437 之类的东西。

很感谢任何形式的帮助。谢谢!

4

1 回答 1

4

您必须将 unicode 字符串传递给os.listdirPython 将返回 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 在您传递编码路径名时会尝试对它们进行编码。

于 2011-06-21T14:26:39.230 回答