I have a path to a certain directory, and I need to get a list of all of it's sub-directories that themselves don't contain any sub-directories.
For example, if I've got the following tree:
-father_dir:
-son_dir1:
-grandson.txt
-son_dir2:
-grandson_dir1:
-greatgrandson1.txt
I'd like to have a list containing: [son_dir1, grandson_dir1]
What I tried: I used os.walk()
to get all of the sub-directories in father_dir
, and now I'm trying to iterate over each sub-directory's contents (with os.listdir()
) and find if it contains directories... so far I wasn't successful (as os.listdir()
doesn't give the path to the directory but rather only its name), besides it seems to be a very cumbersome method.
Any simple solution would be welcome. Thanks!
If you name one or more directories on the command line, ls will list each one. The -R (uppercase R) option lists all subdirectories, recursively. That shows you the whole directory tree starting at the current directory (or the directories you name on the command line).
Using the ls Command. The ls command lists the directories and files contained in a directory. The ls command with the -lR options displays the list (in long format) of the sub-directories in the current directory recursively.
Use os.listdir() function The os. listdir('path') function returns a list containing the names of the files and directories present in the directory given by the path .
The ls command is used to list files or directories in Linux and other Unix-based operating systems. Just like you navigate in your File explorer or Finder with a GUI, the ls command allows you to list all files or directories in the current directory by default, and further interact with them via the command line.
Use os.walk
and a list comprehension:
[os.path.split(r)[-1] for r, d, f in os.walk(tree) if not d]
lowest_dirs = list()
for root,dirs,files in os.walk(starting_directory):
if not dirs:
lowest_dirs.append(root)
This works because os.walk
recurses through the directories, setting each to root
in turn. You want to know if it's a lowest-level directory? That means it contains no other directories, so for that root if dirs
is empty, toss it in an accumulator.
If you additionally want to skip EMPTY lowest-level folders, do:
if files and not dirs:
If you only want the tail (the folder name, not the whole path), use:
lowest_dirs.append(os.path.split(root)[-1])
>>> lowest_dirs = list()
>>> toplevel = r"U:\User\adsmith\My Documents\dump\father_dir"
>>> for root,dirs,files in os.walk(toplevel):
... if not dirs:
... lowest_dirs.append(os.path.split(root)[-1])
>>> print(lowest_dirs)
['son_dir1', 'grandson_dir1']
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