Home  >  Article  >  Backend Development  >  How to Efficiently Get a List of Subdirectories in Python?

How to Efficiently Get a List of Subdirectories in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-28 00:16:11376browse

How to Efficiently Get a List of Subdirectories in Python?

Obtaining a Directory List using 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.

Using os.walk for Comprehensive Subdirectory Retrieval

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)]

Immediate Subdirectory Retrieval with os.listdir and os.path.isdir

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn