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
Show 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
"""
# Add each image as an
tag in the HTML content
for image in image_files:
image_path = os.path.join(directory, image)
html_content += f'
\n'
# End the HTML content
html_content += """
"""
# 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