gpt4 book ai didi

python - 将python文件名转换为unicode

转载 作者:IT老高 更新时间:2023-10-28 21:05:48 26 4
gpt4 key购买 nike

我正在使用适用于 Windows 的 python 2.6。

我使用 os.walk 来读取文件树。文件的文件名中可能包含非 7 位字符(例如德语“ae”)。这些是在 Python 的内部字符串表示中编码的。

我正在使用 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'])]

最佳答案

如果您将 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 - 将python文件名转换为unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1052225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com