我想遍历目录,其中子目录的名称可以包含非 ASCII 字符。在这种情况下,os.walk
将子目录视为文件。示例如下:
我有目录 test
及其子目录:asd
、gé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
以及 dirs
和 files
列表中的值也将是 Unicode。
关于python - os.walk 无法正确处理路径中的 unicode 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25059884/