Python Forum

Full Version: os.walk question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I am trying to understand the logic behind os.walk.
What I want to achieve is a list of dirs and subdirs and sub-subdirs. (the max is 3 dirs deep with some of them)
This program does that with no errors:
myPath =  'whatever'
for (root,subs,files) in os.walk(myPath):
    for s in subs:
        path = os.path.join(root,s)
        print(path)
I get a list of dirs of level 1 first.
Then it seems to loop a second time and prints the level 1 dirs again , followed by their subdirs AND (level3) sub-subdirs.

Question : why does it loop twice, and not three times, as one would expect?
A test shows that if i add a level 4 subdir, it keeps looping only twice with correct results.

Paul
(May-31-2020, 09:58 AM)DPaul Wrote: [ -> ]Question : why does it loop twice, and not three times, as one would expect?
A test shows that if i add a level 4 subdir, it keeps looping only twice with correct results.
Because can't see all code that's used.
It's a recursive function with while and for loops,look at source code def walk.
(May-31-2020, 12:24 PM)snippsat Wrote: [ -> ]Because can't see all code that's used.
It's a recursive function with while and for loops,look at source code def walk.

Aha ! Didn't know that.

thx,
Paul