Windows下Python文件名格式化

2 投票
1 回答
1812 浏览
提问于 2025-04-16 20:00

我有两个不同的文件,名字分别是:

'╠.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,而不是0xCC。我尝试过用编码和解码的方法,但都没有成功。我注意到sys.getfilesystemencoding()的设置是mbcs,但我不知道怎么把它改成cp437。

任何帮助都非常感谢!

1 个回答

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在你传入一个编码过的路径名时,会试图对它进行编码。

撰写回答