Guillermo.D
Guillermo.D

Reputation: 447

find folders in a tree and create a list with their paths

I have big folder tree and I need to make a list with the path of every folder named "arc". The folder tree is something like:

./tree
--> ./A
----> ./one
------> ./arc
--> ./B
--> ./C
----> ./two
------> ./arc
--> ./D
--> ./E
----> ./three
--> ./F
----> ./four
------> ./arc

My final list should be [/tree/A/one/arc, /tree/C/two/arc, /tree/F/four/arc] (note that arc is always in the fourth level of the tree)

I've been trying with the os.walk function but haven't been successful. Any help will be very appreciated.

Upvotes: 1

Views: 82

Answers (1)

Adam Smith
Adam Smith

Reputation: 54173

final_list = [os.path.join(root,dir) for
    root,dirs,files in os.walk("path/to/tree") for
    dir in dirs if dir=="arc"]

os.walk(path) returns a list of tuples, containing:

(the root directory for this recursion,
 a listing of all subdirectories in that root,
 a listing of all the files in that root)

So we're going through os.walk and looking at all the dirs tuples, pulling each one and checking to see if it's "arc". If it is, it's combining the root (which is something like 'path/to/tree/A/One' with the dir name (which should always be 'arc') using os.path.join (which puts the OS-specific path separator between each argument), and adding that to the list comp.

Upvotes: 1

Related Questions