Search code examples
pythondirectory-tree

Directory-tree listing limiter Python


As title explains, I've tried several answers of already posted questions from this site. The thing is, that I'm trying to be able to select how much levels of the folder I dig into. For example, if I want to select only the immediate subdirectories it would look like this:

Subfolder #1
Subfolder #2
Subfolder #3
Subfolder #4

But if I want to the same but show also at the same the immediate subdirectories of the subdirectories already mentioned, it would look like this:

Subfolder #1
  Subfolder #1 of the subfolder #1
  Subfolder #2 of the subfolder #1
Subfolder #2
  Subfolder #1 of the subfolder #2
Subfolder #3
Subfolder #4
  Subfolder #1 of the subfolder #4
  Subfolder #2 of the subfolder #4
  Subfolder #3 of the subfolder #4

PD: I'm pretty new to Python, so I'm probably missing pretty obvious.

EDIT: I reformulated the question, so I can better explain my issue, since it was clearly confusing and did not make any sense the way I said it.


Solution

  • If I understand the question correctly this should do what you want. It is a simple recursive function that just keeps a counter of how "deep" it has gone into the directory and completes when it hits the required number of recursions. Let me know if you need a little more explanation.

    import os
    
    search_dir = "path/to/dir"
    inspection_depth = 1
    
    def walk(path, depth):
        depth += 1
        folders = [f for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]
    
        for folder in folders:
            full_path = os.path.join(path, folder)
            print(full_path)
    
            if depth < inspection_depth:
                walk(full_path, depth)
    
    # Call the recursive function
    walk(search_dir, 0)