What I'm trying to do
I'm trying to get a list of subdirectories up to depth of x containing a file y, such as the following:
root/
root/one/
root/one/README.md
root/two/subdir/
root/two/subdir/README.md
root/three/
In the above tree, I'm trying to identify all subdirectories up to level x that contain the file README.md
.
- If
x = 1
, it should returnroot/one/
- If
x = 2
, it should returnroot/one/
androot/two/subdir
What I've tried
Most answers I can find use os.walk
to loop through directories and identify files. While this works, it doesn't allow for depth limit on recursion. Some workarounds include creating a depth-limited os.walk
function and others use glob patterns to specify depth such as */*/*
for depth of 3 or generated glob pattern. While both of these work, I'm wondering if a cleaner approach exists to my problem?
os.walk
hack
def walklevel(some_dir, level=1):
some_dir = some_dir.rstrip(os.path.sep)
assert os.path.isdir(some_dir)
num_sep = some_dir.count(os.path.sep)
for root, dirs, files in os.walk(some_dir):
yield root, dirs, files
num_sep_this = root.count(os.path.sep)
if num_sep + level <= num_sep_this:
del dirs[:]
glob
hack
def fileNamesRetrieve(top, maxDepth, fnMask):
someFiles = []
for d in range(1, maxDepth+1):
maxGlob = "/".join("*" * d)
topGlob = os.path.join(top, maxGlob)
allFiles = glob.glob(topGlob)
sample of code
def get_subdirs(dir):
file = "README.md"
subdirs = []
# something like this looping through subdirs
for subdir in subdirs(dir, depth=1):
if any(f for f in subdirs.files if f = file)
subdirs.append(subdir)
return subdirs
Question
How should I approach this problem?