Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
os.walk question
#1
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
Reply
#2
(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.
Reply
#3
(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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to sort os.walk list? Denial 6 1,159 Oct-10-2020, 05:28 AM
Last Post: Denial
  os.walk(Path("path_string")) giving error Kumarkv 4 1,138 May-10-2020, 08:46 AM
Last Post: snippsat
  os.walk does not see files that are in the folder kiton 1 874 Jan-21-2020, 07:26 PM
Last Post: micseydel
  print notifcation when enter new directory os.walk() evilcode1 3 1,019 Jun-20-2019, 08:19 PM
Last Post: evilcode1
  Animating Random Walk Excelsiscelia 2 2,945 Nov-24-2018, 08:53 AM
Last Post: Excelsiscelia
  Python3 & os.walk while_e_coyote 2 1,792 Aug-24-2018, 07:32 PM
Last Post: while_e_coyote
  how to test if an object came from os.walk() Skaperen 3 1,561 Jan-10-2018, 03:05 AM
Last Post: Skaperen
  Question about os.walk() behaviour dfkettle 3 2,239 Jan-07-2018, 06:52 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020