Exploring Subdirectories - Python Programming Exercise

In this exercise, you will develop a Python program that explores a specified directory and lists all the subdirectories within it. This exercise is perfect for practicing file handling, directory traversal, and error handling in Python. By implementing this program, you will gain hands-on experience in handling file operations, directory traversal, and error handling in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Using Extra Libraries

 Exercise

Exploring Subdirectories

 Objective

Develop a Python program that explores a specified directory and lists all the subdirectories within it. The program should recursively navigate through all levels of subdirectories and display their names. Implement error handling for invalid directory paths or inaccessible directories, and ensure that the program can handle deeply nested structures.

 Example Python Exercise

 Copy Python Code
import os

def explore_subdirectories(directory_path, level=0):
    """Recursively explores the given directory and lists all subdirectories."""
    try:
        if not os.path.exists(directory_path):
            print(f"Error: The directory '{directory_path}' does not exist.")
            return
        
        if not os.path.isdir(directory_path):
            print(f"Error: '{directory_path}' is not a valid directory.")
            return
        
        # List all the subdirectories
        print("  " * level + f"Exploring directory: {directory_path}")
        
        for root, dirs, files in os.walk(directory_path):
            # Skip files, only show directories
            for dir_name in dirs:
                dir_path = os.path.join(root, dir_name)
                print("  " * (level + 1) + f"Subdirectory: {dir_path}")
            
            # Since os.walk() already traverses subdirectories, we break after the first directory
            break

    except PermissionError:
        print(f"Error: Permission denied while accessing '{directory_path}'")
    except Exception as e:
        print(f"Unexpected error: {e}")

def main():
    """Main function to initiate the subdirectory exploration."""
    directory_path = input("Enter the directory path to explore: ").strip()
    explore_subdirectories(directory_path)

if __name__ == '__main__':
    main()

 Output

Enter the directory path to explore: /home/user/Documents

Exploring directory: /home/user/Documents
  Subdirectory: /home/user/Documents/SubFolder1
  Subdirectory: /home/user/Documents/SubFolder2
  Subdirectory: /home/user/Documents/SubFolder3

If there are nested subdirectories, the output will look like this:

Enter the directory path to explore: /home/user/Documents

Exploring directory: /home/user/Documents
  Subdirectory: /home/user/Documents/SubFolder1
    Subdirectory: /home/user/Documents/SubFolder1/SubSubFolder1
    Subdirectory: /home/user/Documents/SubFolder1/SubSubFolder2
  Subdirectory: /home/user/Documents/SubFolder2
  Subdirectory: /home/user/Documents/SubFolder3

 Share this Python Exercise

 More Python Programming Exercises of Using Extra Libraries

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Working with Date and Time

    In this exercise, you will develop a Python program that works with date and time. This exercise is perfect for practicing date and time manipulation, user inp...

  •  Displaying Directory Contents

    In this exercise, you will develop a Python program that displays the contents of a specified directory. This exercise is perfect for practicing file handling,...

  •  Listing Executable Files in a Directory

    In this exercise, you will develop a Python program that lists all executable files in a specified directory. This exercise is perfect for practicing file hand...

  •  Continuous Date and Time

    In this exercise, you will develop a Python program that continuously displays the current date and time in real-time. This exercise is perfect for practicing ...

  •  Sitemap Generator

    In this exercise, you will develop a Python program that generates a sitemap for a website. This exercise is perfect for practicing web crawling, URL retrieval...

  •  Generating a List of Images as HTML

    In this exercise, you will develop a Python program that generates an HTML file displaying a list of images from a specified directory. This exercise is perfec...