我有两个不同的文件,名为:
'╠.txt' and '¦.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。
非常感谢任何帮助。 谢谢!
最佳答案
您必须将 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 会尝试对它们进行编码。
关于python - Windows 下 Python 的文件名格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6425824/