将python文件名转换为unicode

2024-05-16 15:07:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python 2.6for Windows上。

我使用os.walk读取文件树。文件名中可能包含非7位字符(例如德语“ae”)。它们用Pythons内部字符串表示进行编码。

我正在用Python库函数处理这些文件名,但由于编码错误而失败。

如何将这些文件名转换为正确的(unicode?)python字符串?

我有一个文件“d:\ utest\ü.txt”。将路径作为unicode传递不起作用:

>>> list(os.walk('d:\\utest'))
[('d:\\utest', [], ['\xfc.txt'])]
>>> list(os.walk(u'd:\\utest'))
[(u'd:\\utest', [], [u'\xfc.txt'])]

Tags: 文件字符串txt编码foros文件名windows
3条回答

如果将Unicode字符串传递给os.walk(),将得到Unicode结果:

>>> list(os.walk(r'C:\example'))          # Passing an ASCII string
[('C:\\example', [], ['file.txt'])]
>>> 
>>> list(os.walk(ur'C:\example'))        # Passing a Unicode string
[(u'C:\\example', [], [u'file.txt'])]

我在寻找Python 3.0+的解决方案。会把它放在这里以备别人需要。

rootdir = r'D:\COUNTRY\ROADS\'
fs_enc = sys.getfilesystemencoding()
for (root, dirname, filename) in os.walk(rootdir.encode(fs_enc)):
    # do your stuff here, but remember that now
    # root, dirname, filename are represented as bytearrays
os.walk(unicode(root_dir, 'utf-8'))

相关问题 更多 >