0

Suppose that I have a directory with 3 directories a, b, c. Within each of these directories I have the four directories 1, 2, 3, 4. Is there a way to list all paths, i.e. a/1,..., a/4, ..., c/1, ..., c/4, in python?

Is there a generalization? For example, given a directory to list all paths within at most 3 levels.

1 Answers1

0

You can try this:

import os
n_levels = 2
cur_level = ['/your/start/path']
for level in range(n_levels):
  cur_level = [os.path.join(p, f) 
               for p in cur_level
               if os.path.isdir(p)
               for f in os.listdir(p)]
print(cur_level)

It starts at cur_level = '/your/start/path' as level 0, enumerates all its files and directories and stores their full paths back in list cur_level. Then the same is done for each path in the cur_level again, the results are again saved as a list.

Alexey S. Larionov
  • 6,555
  • 1
  • 18
  • 37