Skip to content Skip to sidebar Skip to footer

List All Subdirectories On Given Level

I have backup directory structure like this (all directories are not empty): /home/backups/mysql/ 2012/ 12/ 15/ 2013/ 04/ 29/

Solution 1:

from glob importigloblevel3= iglob('/home/backups/mysql/*/*/*')

(This will skip "hidden" directories with names starting with .)

If there may be non-directories at level 3, skip them using:

from itertools import ifilter
import os.path

l3_dirs = ifilter(os.path.isdir, level3)

In Python 3, use filter instead of ifilter.

Solution 2:

You can use glob to search down a directory tree, like this:

import os, glob
defget_all_backup_paths(dir, level):
   pattern = dir + level * '/*'return [d for d in glob.glob(pattern) if os.path.isdir(d)]

I included a check for directories as well, in case there might be files mixed in with the directories.

Solution 3:

import functools, os

def deepdirs(directory, depth = 0):
    if depth == 0:
        return list(filter(os.path.isdir, [os.path.join(directory, d) for d inos.listdir(directory)]))
    else:
        return functools.reduce(list.__add__, [deepdirs(d) for d in deepdirs(directory, depth-1)], [])

Post a Comment for "List All Subdirectories On Given Level"