Listing Image Files with Python (and HTML)

I needed a utility to help list image files that I keep in various directories. I wrote a short Python 3 script that met my needs.  I thought I’d share it.

#!/usr/bin/env python3
# MIT/X11 License
# See

from os import listdir

if __name__ == "__main__":
    f.write("<html><head><title>Image List</title></head><body>\n")
    for fname in listdir("."):
        if fname.lower().endswith((".jpg",".jpeg",".gif",".png")):
            f.write("<h2>" + fname + "<h2>")
            f.write("<img src='" + fname + "' style='max-width: 1000;'>")

Usage is simply:

An HTML file named images.htm will be created in the current directory. When opened, this file will display the filenames with a rendered picture of each image.

The images are scaled to a max of 1000 pixels in width.

I didn’t provide a configuration file option for the HTML filename or for any of the generated markup. The script itself is short enough that it should be pretty easy to change.

Things I learned: I had no idea until working on this script that the endswith() method can use a tuple of comparator strings.


About Jim Lawless

I've been programming computers for about 37 years ... 31 of that professionally. I've been a teacher, I've worked as a consultant, and have written articles here and there for publications like Dr. Dobbs Journal, The C/C++ Users Journal, Nuts and Volts, and others.
This entry was posted in Programming, Tech and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s