Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

My first useful python program!

Name: Anonymous 2013-01-21 23:01

Good evening my good friends of /prog/! Thanks to your encouragement, I made my first useful python program today. Basically it generates an HTML script that displays every image in a directory. I'll post it in hopes that you can use it !~{^-^}~♥

#index generator for directory of images for HTML
import os
import fnmatch

FNL = os.listdir(".")

f = open('index.html','w')
f.write("<html><head><title>Index of...</title></head><body>")

#make a list of workable files in this
for FileName in FNL:
    if fnmatch.fnmatch(FileName, '*.jpg'):
        f.write("<img src=\""+FileName+"\"></img><br>")
    if fnmatch.fnmatch(FileName, '*.jpeg'):   
        f.write("<img src=\""+FileName+"\"></img><br>")
    if fnmatch.fnmatch(FileName, '*.gif'):   
        f.write("<img src=\""+FileName+"\"></img><br>")
    if fnmatch.fnmatch(FileName, '*.png'):   
        f.write("<img src=\""+FileName+"\"></img><br>")
    if fnmatch.fnmatch(FileName, '*.bmp'):   
        f.write("<img src=\""+FileName+"\"></img><br>")
       
#close up by writing the ending tags
f.write("</body></html>")

Name: Anonymous 2013-01-22 1:08

Well, that's one way to do it.

You don't need the closing </img> tag. All browsers treat img as a closed tag. You can write <img .../> if it makes you feel better.

There's a lot of duplicate code there. That entire for loop can be written:

PATTERNS = ['*.jpg', '*.jpeg', '*.gif', '*.png', '*.bmp']
for FileName in FNL:
    for FilePattern in PATTERNS:
        if fnmatch.fnmatch(FileName, FilePattern):
            f.write("<img src=\""+FileName+"\"></img><br>")


Then if you need to change the write statement, you only need to do it once, and adding new formats is as simple as:

PATTERNS = ['*.jpg', '*.jpeg', '*.gif', '*.png', '*.bmp', '*.tiff']

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List