Home > Article > Backend Development > How to Efficiently Get a List of Subdirectories in Python?
When working with directory structures, it's often necessary to access a list of subdirectories. In Python, this task can be accomplished with the help of specific modules and functions.
The os.walk function provides a recursive way to traverse a directory tree, yielding a 3-tuple for each subdirectory: directory name, a list of child directories, and a list of files in the subdirectory. To retrieve a list of all subdirectories, both immediate and nested, one can use a list comprehension:
[x[0] for x in os.walk(directory)]
Alternatively, to limit the retrieval to immediate subdirectories, the os.listdir and os.path.isdir functions can be employed. os.listdir returns a list of all files and directories in the current working directory. By filtering this list using os.path.isdir, which checks whether an item is a directory, you can obtain the immediate subdirectories:
next(os.walk('.'))[1]
The above is the detailed content of How to Efficiently Get a List of Subdirectories in Python?. For more information, please follow other related articles on the PHP Chinese website!