Python Program to Display all the directories in a directory


In Python, we can use the pathlib module, os module, and glob module to display all the folders in a directory. The os module contains various functions like os.scandir, os.walk , os.listdir or glob(), and iglob() methods, etc to list all the directories in a directory. A directory is a folder in a file system that stores various files or more folders.

Method 1: Using the Pathlib Module

We can use the Path.iterdir() function to get the path object of the contents in the directory. We can then iterate over the path objects and filter out the directories using the path.is_dir() method.

Syntax

path(‘your_dir_path’).iterdir()

The path() function above takes the path of the directory and iterates over every file and directory using the iterdir() function.

Example

In the below example, we import the pathlib from the Path module in Python. We can then get the path object of the directory content using the path.iterdir() function and then iterate over the object to filter out the path of the contents in the directory.

from pathlib import Path
 
rootdir = 'path/to/dir'
for path in Path(rootdir).iterdir():
   if path.is_dir():
      print(path)

Output

C:\Users\Muralidhar\Downloads\DesignCode - CSS Handbook
C:\Users\Muralidhar\Downloads\Documents
C:\Users\Muralidhar\Downloads\LakshyaPoddar_FD_Round3_Code Base
C:\Users\Muralidhar\Downloads\locales
C:\Users\Muralidhar\Downloads\Music

Method 2: Using the OS Module

Syntax

os.listdir(‘your_directory_path’)

The listdir() method of the os module takes the path of the directory and returns all the subdirectories in that particular directory path.

Example

Using os.listdir() method: listdir() function in the os module simply returns all the subdirectories in the root directory by default. If we want to list the subdirectories of any specified directory then we need to pass the path of the directory to the os.listdir() function.

# import OS module
import os

# Get the list of all files and directories
path = "your_directory_path"
dir_list = os.listdir(path)

print("The path of the directory '", path, "' :")

# prints all files
print(dir_list)

Output

'SOP_VISHAL.docx', 'SR.jpeg', 'src', 'src.rar', 'staff.svg', 'sublime_text_build_4126_x64_setup.exe', 'submission_2.zip', 'swiftshader'

Using os.scandir() method

The scandir() method returns the subdirectory as well as the file information in the directory path. To filter out only the subdirectories we can use the is_dir() method which checks if the path is of a file or a directory. The Scandir() method is faster than the listdir() method.

Syntax

os.scandir(‘your_directory_path’)

The scandir() function of the os module takes the path of the directory as input and returns all the subdirectories and files in the particular directory.

Example

import os
 
rootdir = 'path/to/dir'
for it in os.scandir(rootdir):
   if it.is_dir():
      print(it.path)

Output

C:\Users\Muralidhar\Downloads\Programs
C:\Users\Muralidhar\Downloads\resources
C:\Users\Muralidhar\Downloads\src
C:\Users\Muralidhar\Downloads\swiftshader
C:\Users\Muralidhar\Downloads\Telegram Desktop
C:\Users\Muralidhar\Downloads\TransferNow-20230404wNPPor3p
C:\Users\Muralidhar\Downloads\Video

Using os.walk() method

The walk() method iterates over all the files in the directory and returns all the list of files in the directory structure. By default, the walk function returns the files from the root directory by iterating in a top-down manner. We can pass a specific path and the specific scanning approach (top-down or bottom-up) to the walk() function.

Syntax

os.walk(‘your_directory_path’)

The walk() function of the os module takes the path of the directory as input and returns the list of files in the particular directory.

Example

# import OS module
import os

# This is my path
path = "your_specific_path"

# to store files in a list
list = []

# dirs=directories
for (root, dirs, file) in os.walk(path):
   for f in file:
      if '.txt' in f:
         print(f)

Output

license.txt
authors.txt
config.txt
help.txt
logo.txt
options.txt
topics.txt

Method 3: Using the Glob Module

Using the glob() method

The glob() method uses the pattern-matching approach to make the listing of files and directories more efficient. We can use wildcards like *,.txt, etc. which allows searching for file paths matching the wildcard pattern.

Syntax

glob.glob(‘your_directory_path’+ pattern)

The glob() function of the glob module takes the path of the directory and the pattern as input and returns all the files in the particular directory matching the pattern with file names.

Example

import glob

# This is my path
path = "your_specific_path"

# Using '*' pattern
print('\nNamed with wildcard *:')
for files in glob.glob(path + '*'):
   print(files)

# Using '?' pattern
print('\nNamed with wildcard ?:')
for files in glob.glob(path + '?.txt'):
   print(files)


# Using [0-9] pattern
print('\nNamed with wildcard ranges:')
for files in glob.glob(path + '/*[0-9].*'):
   print(files)

Output

Named with wildcard *:
C:\Users\Muralidhar\Downloads

Named with wildcard ?:

Named with wildcard ranges:
C:\Users\Muralidhar\Downloads\1643005747_rohankumarsingh074c43032beb4cee8cb1329312cf92351643005746.pdf
C:\Users\Muralidhar\Downloads\1674125121289.jpg
C:\Users\Muralidhar\Downloads\807.pdf

Using iglob() method

The iglob() function is used to print the file names recursively if the recursive parameter is set to true in the parameter passed to iglob() function.

Syntax

glob.iglob(‘your_directory_path’,recursive=true/false)

The iglob() function of the glob module takes the path of the directory and a boolean value for the recursive parameter as true/false as input and returns all the files inside every subdirectory recursively.

Example

import glob

# This is my path
path = "your_specific_path"


# It returns an iterator which will
# be printed simultaneously.
print("\nUsing glob.iglob()")

# Prints all types of txt files present in a Path
for file in glob.iglob(path, recursive=True):
   print(file)

Output

Using glob.iglob()
C:\Users\Muralidhar\Downloads

Conclusion

In this article, we understood how to list all the files and subdirectories present in a directory using os, glob, and pathlib modules in Python. The pathlib module contains the path.iterdir() function, the os module contains the os.listdir(),os.walk() and os.listdir() method to get the subdirectories in the specified directory.

Updated on: 17-Apr-2023

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements