Often in Python, the need arises to obtain a list of all subdirectories within the current directory. While there's an inbuilt method for retrieving files, getting directories requires a different approach.
To accomplish this, os.walk(directory) is an effective solution. By iterating through the returned tuples, where the first entry represents the directory name, you can extract all the subdirectories.
[x[0] for x in os.walk(directory)]
For a recursive approach, this method provides a comprehensive list of all subdirectories. Alternatively, you could limit the results to immediate child directories:
next(os.walk('.'))[1]
Additional solutions worth considering include using os.listdir and os.path.isdir. Refer to "How to get all of the immediate subdirectories in Python" for more details.
The above is the detailed content of How to Efficiently Retrieve Subdirectories in Python?. For more information, please follow other related articles on the PHP Chinese website!