
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get List of All Sub-Directories in Current Directory Using Python
In Python, when working with files and directories, we may often need to get a list of subdirectories within a specific location, especially the current working directory. In this article, we are going to use the different methods available in Python to get a list of all subdirectories in the current directory.
Using os Module
While working with files, one of the most widely used approaches is using os module. This module provides a way to interact with the operating system to perform tasks such as navigating directories, reading file structures, and more. In this module, we have a method os.walk() to get the list of all subdirectories in the current directory.
Example
Here is the example which shows how to use the os.walk() method to get the list of subdirectories in the given current directory -
import os # List all sub-directories in the current directory subdirectories = [a for a in os.listdir('.') if os.path.isdir(a)] print("Sub-directories in current directory:") print(subdirectories)
Following is the output of the above program -
['old_articles', '__pycache__']
Using pathlib Module
Python's pathlib module is introduced in Python 3.4 version which provides an object-oriented approach to handling filesystem paths. It is one of the preferred ways to get the list of all subdirectories.
Example
Following is an example, which shows how to use the pathlib module to get the list of all subdirectories in the current directory -
from pathlib import Path # Get the current directory as a Path object current_dir = Path('.') # List all sub-directories subdirectories = [a.name for a in current_dir.iterdir() if a.is_dir()] print("Sub-directories in current directory:") print(subdirectories)
Here is the output of the above program -
['old_articles', '__pycache__']