【问题标题】:Filename formatting in Python under WindowsWindows下Python中的文件名格式化
【发布时间】:2011-06-21 13:16:47
【问题描述】:

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

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

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

【问题讨论】:

  • OT 对于您的实际问题,但是在 Windows 上使用路径时,请执行以下操作之一:(1) 使用原始字符串 r"E:\whatever" (2) 使用正斜杠 "E:/whatever" (3) 加倍反斜杠 @ 987654325@ 以避免在您的路径被解释错误时出现另一个问题,因为您的字符串文字包含\n、\t 或其他类似的字符。
  • 使用 Python 3,sys.getfilesystemencoding() 返回'mbcs',我似乎没有遇到您的问题。 @bgporter:是的,他设置它的方式看起来字符串从未正确关闭。

标签: python unicode codepages mbcs


【解决方案1】:

您必须将 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 会在您传递编码路径名时尝试对其进行编码。

【讨论】:

  • 这确实是问题 - 如下代码现在修复了我的 mojibake :- path = ur"E:\pub\private\desktop\TestMp3" files = os.listdir(path) for f in files : print f, repr(f), type (f) msdos = f.encode('cp437') sjis = msdos.decode('shift-jis') print f, repr(sjis), sjis Tks 很多 -跨度>
猜你喜欢
  • 2010-10-02
  • 1970-01-01
  • 2017-02-25
  • 1970-01-01
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多