python - Windows 下 Python 的文件名格式化

标签 python unicode codepages mbcs

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

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

相关文章:

python - 在heroku上使用python Flask运行chrome驱动程序(pyppeteer)

javascript - 每种语言的字体大小

c# - 使用 C# 为 PInvoke 字符串编码指定代码页

python - 将 ☺ 编码为 IBM-437 失败,而 é 等其他有效字符成功

python - 如何从 Pandas DataFrame 中获取值而不是索引和对象类型

php - 使用 PHP 和 Tornado

html - Unicode 字符对齐

c++ - 如何在应用程序中更改 Windows ANSI api 的 CP_ACP(0)?

python - 如果 monkeyrunner 包含在 python 脚本中,则不能使用 raw_input

sql-server - ssis unicode 平面文件由脚本组件处理