Python Forum
os.walk question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: os.walk question (/thread-27247.html)



os.walk question - DPaul - May-31-2020

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


RE: os.walk question - snippsat - May-31-2020

(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.


RE: os.walk question - DPaul - May-31-2020

(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