Exploring a Directory - Python Programming Exercise

In this exercise, you will develop a Python program that explores a specified directory and lists all of its contents, including files and subdirectories. 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 A Directory

 Objective

Develop a Python program that explores a specified directory and lists all of its contents, including files and subdirectories. The program should display the names of the files and directories, as well as additional details such as file size, type, and creation date. Implement error handling for invalid directory paths and inaccessible directories.

 Example Python Exercise

 Copy Python Code
import os
import time

def get_file_info(file_path):
    """Get details like size, type, and creation date for a given file."""
    try:
        file_size = os.path.getsize(file_path)  # File size in bytes
        file_creation_time = os.path.getctime(file_path)  # File creation time (epoch)
        file_type = "Directory" if os.path.isdir(file_path) else "File"
        file_creation_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(file_creation_time))

        return file_size, file_type, file_creation_date
    except Exception as e:
        print(f"Error retrieving information for {file_path}: {e}")
        return None, None, None

def explore_directory(directory_path):
    """Explore the specified directory and list its contents."""
    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
    
    print(f"Exploring directory: {directory_path}\n")
    try:
        # List the files and directories
        for root, dirs, files in os.walk(directory_path):
            # Print the details for subdirectories
            for directory in dirs:
                dir_path = os.path.join(root, directory)
                file_size, file_type, file_creation_date = get_file_info(dir_path)
                print(f"Directory: {directory}")
                print(f"  Path: {dir_path}")
                print(f"  Size: {file_size} bytes")
                print(f"  Type: {file_type}")
                print(f"  Created on: {file_creation_date}\n")
            
            # Print the details for files
            for file in files:
                file_path = os.path.join(root, file)
                file_size, file_type, file_creation_date = get_file_info(file_path)
                print(f"File: {file}")
                print(f"  Path: {file_path}")
                print(f"  Size: {file_size} bytes")
                print(f"  Type: {file_type}")
                print(f"  Created on: {file_creation_date}\n")
                
    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 directory exploration."""
    directory_path = input("Enter the directory path to explore: ").strip()
    explore_directory(directory_path)

if __name__ == '__main__':
    main()

 Output

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

Exploring directory: /home/user/Documents

Directory: SubFolder1
  Path: /home/user/Documents/SubFolder1
  Size: 4096 bytes
  Type: Directory
  Created on: 2024-01-15 10:35:12

File: example_file.txt
  Path: /home/user/Documents/example_file.txt
  Size: 2048 bytes
  Type: File
  Created on: 2023-12-01 14:22:45

File: image.jpg
  Path: /home/user/Documents/image.jpg
  Size: 102400 bytes
  Type: File
  Created on: 2023-11-18 08:11:30

 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.

  •  Exploring Subdirectories

    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 fo...

  •  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...