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)
(注意,dirnames是字符串而不是int,所以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。