Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to create a list of directories at the n-1 level (folders that do not contain any subfolders) with either bash or python

I currently have a problem where I want to get a list of directories that are at an n-1 level. The structure looks somewhat like the diagram below, and I want a list of all the folders that are blue in color. The height of the tree however, varies across the entire file system.

enter image description here

Due to the fact that all the folders that are blue, generally end their name with the string images, I have written the code in Python below:

def getDirList(dir):
    dirList = [x[0] for x in os.walk(dir)]
    return dirList

oldDirList = getDirList(sys.argv[1])

dirList = []

# Hack method for getting the folders
for i, dir in enumerate(oldDirList):
    if dir.endswith('images'):
        dirList.append(oldDirList[i] + '/')

Now, I do not want to use this method, since I want a general solution to this problem, with Python or bash scripting and then read the bash script result into Python. Which one would be more efficient in practice and theoretically?

like image 494
SDG Avatar asked Nov 20 '18 00:11

SDG


1 Answers

To rephrase what I think you're asking - you want to list all folders that do not contain any subfolders (and thus contain only non-folder files).

You can use os.walk() for this pretty easily. os.walk() returns an iterable of three-tuples (dirname, subdirectories, filenames). We can wrap a list comprehension around that output to select only the "leaf" directories from a file tree - just collect all the dirnames that have no subdirectories.

import os

dirList = [d[0] for d in os.walk('root/directory/path') if len(d[1]) == 0]
like image 106
Green Cloak Guy Avatar answered Oct 06 '22 00:10

Green Cloak Guy