gpt4 book ai didi

python - os.walk 以什么顺序进行迭代?

转载 作者:IT老高 更新时间:2023-10-28 20:23:31 34 4
gpt4 key购买 nike

我担心os.walk()给出的文件和目录的顺序。如果我有这些目录,11011122 , 20, 21, 22, 3, 30, 31 32,输出列表的顺序是什么?

是按数值排序的吗?

1 2 3 10 20 30 11 21 31 12 22 32

或按 ASCII 值排序,如 ls 给出的?

1 10 11 12 2 20 21 22 3 30 31 32

另外,我怎样才能得到一个特定的排序?

最佳答案

os.walk 使用 os.listdir。这是 os.listdir 的文档字符串:

listdir(path) -> list_of_strings

Return a list containing the names of the entries in the directory.

path: path of directory to list

The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

(我的重点)。

但是,您可以使用 sort 来确保您想要的顺序。

for root, dirs, files in os.walk(path):
for dirname in sorted(dirs):
print(dirname)

(请注意,目录名是字符串而不是整数,因此 sorted(dirs) 将它们作为字符串进行排序——这一次是可取的。

正如 Alfe 和 Ciro Santilli 指出的那样,如果您希望目录按排序顺序递归,则修改 dirs 就地 :

for root, dirs, files in os.walk(path):
dirs.sort()
for dirname in dirs:
print(os.path.join(root, dirname))

你可以自己测试一下:

import os

os.chdir('/tmp/tmp')
for dirname in '1 10 11 12 2 20 21 22 3 30 31 32'.split():
try:
os.makedirs(dirname)
except OSError: pass


for root, dirs, files in os.walk('.'):
for dirname in sorted(dirs):
print(dirname)

打印

1
10
11
12
2
20
21
22
3
30
31
32

如果您想按数字顺序列出它们,请使用:

for dirname in sorted(dirs, key=int):

要对字母数字字符串进行排序,请使用 natural sort .

关于python - os.walk 以什么顺序进行迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18282370/

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