python - os.walk 无法正确处理路径中的 unicode 字符

标签 python windows python-2.7 unicode encoding

我想遍历目录,其中子目录的名称可以包含非 ASCII 字符。在这种情况下,os.walk 将子目录视为文件。示例如下:

我有目录 test 及其子目录:asdgéocello

for root, dirs, files in os.walk(directory):
    print(root, dirs, files)

打印:

test ['asd'] ['geocello']
test\asd [] ['testfile.txt', '123.txt']

我在 Windows XP 下运行此代码。在 Linux 上一切都很好。 如何让Python正确处理路径?

最佳答案

传入目录unicode值:

directory = u'C:/path/to/root'

现在,os.walk() 将始终使用 unicode 路径,Windows 将正确处理 géocello 文件夹的测试。

请注意,在这种情况下,root 以及 dirsfiles 列表中的值也将是 Unicode。

关于python - os.walk 无法正确处理路径中的 unicode 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25059884/

相关文章:

python - 处理 pandas 中值的包装

windows - 在 Windows 上锁定计算机之前运行脚本

Windows - 构建 .obj 文件时出现 "The command line is too long"

python - 从视频错误中提取帧

python - 匹配最后一组(可能)嵌套的括号

javascript - 使用 JavaScript 从通过 USB 端口连接到笔记本电脑的多个摄像头捕获视频

python - 如何从sqlalchemy中的当前时间计算过去1天的间隔

python - Flask 数据库问题

python - 将 SQL 查询限制在 Graphene-SQLAlchemy 中定义的字段/列

c# - Windows 模拟 : A Flaw in the Ointment