Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List directories with a specified depth in Python

Tags:

python

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?

like image 444
StefanE Avatar asked Aug 23 '11 10:08

StefanE


People also ask

How do I search for a specific directory in Python?

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().

How do I list multiple directories in Python?

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.


2 Answers

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) 
like image 95
phihag Avatar answered Sep 27 '22 18:09

phihag


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.

like image 35
Marek Waligórski Avatar answered Sep 27 '22 20:09

Marek Waligórski