In what order does os.walk iterates iterate? [duplicate]

os.walk uses os.listdir. Here is the docstring for 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.

(my emphasis).

You could, however, use sort to ensure the order you desire.

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

(Note the dirnames are strings not ints, so sorted(dirs) sorts them as strings — which is desirable for once.

As Alfe and Ciro Santilli point out, if you want the directories to be recursed in sorted order, then modify dirs in-place:

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

You can test this yourself:

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)

prints

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

If you wanted to list them in numeric order use:

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

To sort alphanumeric strings, use natural sort.

Leave a Comment

tech