Displaying Directory Contents - Python Programming Exercise

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

Displaying Directory Contents

 Objective

Develop a Python program that displays the contents of a specified directory. The program should list all files and subdirectories within the given directory. Include options to filter the results based on file type or file size, and handle errors for invalid directory paths or inaccessible directories.

 Example Python Exercise

 Copy Python Code
import os

def list_directory_contents(directory, file_type=None, min_size=None, max_size=None):
    """Display the contents of a directory with filtering options."""
    try:
        # Check if the directory exists
        if not os.path.isdir(directory):
            print(f"Error: The directory '{directory}' does not exist or is not accessible.")
            return

        # List all files and subdirectories
        all_items = os.listdir(directory)

        # Filter items based on the file type
        filtered_items = []
        for item in all_items:
            item_path = os.path.join(directory, item)
            
            if os.path.isfile(item_path):
                # Filter by file type (extension)
                if file_type and not item.endswith(file_type):
                    continue
                # Filter by file size if specified
                if min_size and os.path.getsize(item_path) < min_size:
                    continue
                if max_size and os.path.getsize(item_path) > max_size:
                    continue
                filtered_items.append((item, "File"))
            elif os.path.isdir(item_path):
                filtered_items.append((item, "Directory"))

        # Display the filtered contents
        if filtered_items:
            print(f"\nContents of '{directory}':")
            for item, item_type in filtered_items:
                print(f"{item} ({item_type})")
        else:
            print(f"\nNo matching files or directories found in '{directory}'.")

    except PermissionError:
        print(f"Error: Permission denied to access '{directory}'.")
    except Exception as e:
        print(f"Error: {e}")

def main():
    """Main function to interact with the user."""
    # Get user input for the directory
    directory = input("Enter the directory path: ")

    # Get optional filters for file type and file size
    file_type = input("Enter file type to filter by (e.g., .txt, .jpg) or leave blank for no filter: ").strip()
    if file_type == "":
        file_type = None

    try:
        min_size = int(input("Enter minimum file size in bytes (or 0 for no minimum): ").strip())
    except ValueError:
        min_size = 0

    try:
        max_size = int(input("Enter maximum file size in bytes (or 0 for no maximum): ").strip())
    except ValueError:
        max_size = 0

    # List the directory contents with the given filters
    list_directory_contents(directory, file_type, min_size, max_size)

# Run the program
if __name__ == "__main__":
    main()

 Output

Enter the directory path: /path/to/directory
Enter file type to filter by (e.g., .txt, .jpg) or leave blank for no filter: .txt
Enter minimum file size in bytes (or 0 for no minimum): 1000
Enter maximum file size in bytes (or 0 for no maximum): 5000

Contents of '/path/to/directory':
file1.txt (File)
file2.txt (File)
subfolder1 (Directory)
subfolder2 (Directory)

 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.

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

  •  Retrieving System Information

    In this exercise, you will develop a Python program that retrieves and displays system information, such as the operating system, CPU details, memory usage, and disk ...

  •  Sitemap Generator V2

    In this exercise, you will develop an enhanced version of a sitemap generator in Python (Sitemap Generator V2). This exercise is perfect for practicing web cra...