I'm want a function to return a list with directories with a specified path and a fixed depth and soon realized there a few alternatives. I'm using os.walk quite a lot but the code started to look ugly when counting the depth etc.
What is really the most "neat" implementation?
To find out which directory in python you are currently in, use the getcwd() method. Cwd is for current working directory in python. This returns the path of the current python directory as a string in Python. To get it as a bytes object, we use the method getcwdb().
Declare the root directory where we want to create the list of folders in a variable. Initialize a list of items. Then iterate through each element in the list. The os module makes a folder of each element of the list in the directory where our python ide is installed.
If the depth is fixed, glob
is a good idea:
import glob,os.path filesDepth3 = glob.glob('*/*/*') dirsDepth3 = filter(lambda f: os.path.isdir(f), filesDepth3)
Otherwise, it shouldn't be too hard to use os.walk
:
import os,string path = '.' path = os.path.normpath(path) res = [] for root,dirs,files in os.walk(path, topdown=True): depth = root[len(path) + len(os.path.sep):].count(os.path.sep) if depth == 2: # We're currently two directories in, so all subdirs have depth 3 res += [os.path.join(root, d) for d in dirs] dirs[:] = [] # Don't recurse any deeper print(res)
This is not exactly neat, but under UNIX-like OS, you could also rely on a system tool like "find", and just execute it as an external program, for example:
from subprocess import call call(["find", "-maxdepth", "2", "-type", "d"])
You can then redirect the output to some string variable for further handling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With