Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am concerned about the order of files and directories given by os.walk(). If I have these directories, 1, 10, 11, 12, 2, 20, 21, 22, 3, 30, 31, 32, what is the order of the output list?

Is it sorted by numeric values?

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

Or sorted by ASCII values, like what is given by ls?

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

Additionally, how can I get a specific sort?

like image 485
Vahid Mirjalili Avatar asked Aug 16 '13 21:08

Vahid Mirjalili


People also ask

What does OS Walk () do?

OS. walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

What does OS walk return in Python?

os. walk() returns a list of three items. It contains the name of the root directory, a list of the names of the subdirectories, and a list of the filenames in the current directory.

What does it mean to walk a directory?

A common task when working with files is to walk through a directory, that is, recursively get every file in every directory starting in some location.


1 Answers

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.

like image 103
unutbu Avatar answered Sep 22 '22 17:09

unutbu