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
Show 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