- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get a list of all sub-directories in the current directory using Python?
To get a list of all subdirectories in a directory, recursively, you can use the os.walk function. It returns a three tuple with first entry being all the subdirectories.
You can use it as follows:
import os subdirs = [x[0] for x in os.walk('.')] print(subdirs)
You can also list the directories(immediate only) using the os.listdir function and filtering the list using the os.path.isdir function.
For example
import os d = '.' subdirs = [os.path.join(d, o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))]
Advertisements