Search code examples
pythoniteratorpathlib

How to control order of result from iterator in python


I use pathlib.Path().iterdir() to get sub-dictionary of the path.

Under /home/yuanyi/workspace/app, there are 4 folders: 01, 02, 03, 04.

from pathlib import Path
for subdir in Path('/home/yuanyi/workspace/app').iterdir():
    print(subdir)

But the result is not ordered.

/home/yuanyi/workspace/app/02
/home/yuanyi/workspace/app/03
/home/yuanyi/workspace/app/01
/home/yuanyi/workspace/app/00

Wht the result is not the following:

/home/yuanyi/workspace/app/01
/home/yuanyi/workspace/app/02
/home/yuanyi/workspace/app/03
/home/yuanyi/workspace/app/04

I want to know how the iterator works, and what's the best method to get ordered result.


Solution

  • You can use "sorted()"

    Built-in Functions Python - sorted()

    from pathlib import Path
    for subdir in sorted(Path('/some/path').iterdir()):
        print(subdir)
    

    NOTE: @NamitJuneja points out, This changes iterating over a generator to iterating over a list. Hence if there are a huge number of files in the memory, loading them all into the memory (by loading them into a list) might cause problems.

    On my Mac, the iterdir() method returns the list already sorted. So that looks system dependent. What OS are you using?