Generating a List of Images as HTML - Python Programming Exercise

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 perfect for practicing file handling, HTML generation, and error handling in Python. By implementing this program, you will gain hands-on experience in handling file operations, HTML generation, 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

Generating A List Of Images As HTML

 Objective

Develop a Python program that generates an HTML file displaying a list of images from a specified directory. The program should scan the directory for image files, create an HTML file, and insert image tags () for each image found. Ensure the generated HTML is well-structured, and handle cases where the directory contains no images or the path is invalid.

 Example Python Exercise

 Copy Python Code
import os

def generate_image_html(directory):
    """Generate an HTML file displaying images from the specified directory."""
    
    # Define allowed image extensions
    image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp')
    
    # Check if the directory exists
    if not os.path.isdir(directory):
        print(f"Invalid directory: {directory}")
        return
    
    # List all files in the directory
    image_files = [file for file in os.listdir(directory) if file.lower().endswith(image_extensions)]
    
    # Check if there are any image files in the directory
    if not image_files:
        print(f"No images found in the directory: {directory}")
        return
    
    # Start the HTML content
    html_content = """
    
    
    
        
        
        Image Gallery
        
    
    
        

Image Gallery

""" # Write the HTML content to a file try: with open("image_gallery.html", "w") as file: file.write(html_content) print(f"HTML file generated successfully: image_gallery.html") except Exception as e: print(f"Error writing HTML file: {e}") def main(): """Main function to accept user input and generate HTML file.""" directory = input("Enter the directory path to scan for images: ").strip() # Generate the HTML file displaying images generate_image_html(directory) if __name__ == "__main__": main()

 Output




    
    
    Image Gallery
    


    

Image Gallery

 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.

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

  •  Exploring a Directory

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

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