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?
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With