How to get all of the immediate subdirectories in Python
Here's a quick way to get immediate subdirectories:
This leverages os.listdir('.')
to cycle through items in the current directory ('.'
). It then uses os.path.isdir()
to verify if these items are directories, finally returning a list of the subdirectory names.
Harness power of os.scandir() for subdirectory listings
os.listdir()
is cool but os.scandir()
is where the real deal is at, scoring points in both efficiency and practicality. For large directories, os.scandir()
outruns os.listdir()
, thanks to its iterator that yields DirEntry
objects:
os.scandir()
makes it a breeze to exclude specific directories:
Dir hunting with wildcards using Glob
That wildcard character '*' you've always ignored? It's a beast at pattern matching with glob
:
Here, the */
pattern signifies interest in only directory-type entities due to the trailing slash.
Walk the directory tree with os.walk()
Deeper tree traversals call for os.walk()
. But when you only want immediate subdirectories, add next()
to keep it from wandering off.
This command retrieves immediate subdirectories in the current directory, without prying into deeper levels like os.walk()
usually does.
Sophisticated dir listing with sorting and pattern matching
Sometimes, order is everything. Sort directories by their modification time or name with the sorted()
function:
For complex matching or exclusion patterns, glob
and fnmatch
make a powerful duo:
Forge powerful scripts with Python's directory tools
Combining all we've learned we can construct robust Python scripts that rule the file system, like this one that does automated file copying:
Was this article helpful?