📅  最后修改于: 2023-12-03 14:46:00.056000             🧑  作者: Mango
Sometimes, we may need to list all the subdirectories within a directory for various reasons, such as accessing files organized into specific subdirectories or analyzing the structure of a directory tree. In Python, we can accomplish this using various libraries and functions.
One way to list all subdirectories within a directory is to use the os.listdir()
function, which returns a list of all entries in the specified directory path. We can iterate over this list and filter out subdirectories using the os.path.isdir()
function. Here's an example code snippet:
import os
def list_subdirectories(path):
subdirectories = []
for entry in os.listdir(path):
if os.path.isdir(os.path.join(path, entry)):
subdirectories.append(entry)
return subdirectories
In this code, path
is the directory path that we want to list subdirectories for. We create an empty subdirectories
list to store the subdirectories we find. Then we loop over all entries in the specified directory using os.listdir()
. For each entry, we use os.path.join()
to form the absolute path, and then use os.path.isdir()
to check if it's a directory. If so, we append its name to the subdirectories
list. Finally, we return the list of subdirectories.
Another way to list all subdirectories within a directory is to use the glob.glob()
function, which uses shell-style pattern matching to match directory paths. We can use the pattern */
to match all immediate subdirectories of a directory. Here's an example code snippet:
import glob
def list_subdirectories(path):
return [dir for dir in glob.glob(f"{path}*/") if os.path.isdir(dir)]
In this code, path
is the directory path that we want to list subdirectories for. We use an f-string to construct the pattern {path}*/
, which matches all immediate subdirectories of path
. We use a list comprehension to iterate over all matched directories and filter out non-directory entries using os.path.isdir()
. Finally, we return the list of subdirectories.
In this article, we've explored two ways to list all subdirectories within a directory in Python. Both methods use different libraries and functions to accomplish the task, but they both achieve the same result. Depending on the use case, one method may be more appropriate than the other.