Poor Man's Photo Album Generator
It's inconvenient to browse nested directories full of photos and pictures with normal file browser. A friend wanted a script that can search a directory recursively and output a HTML file listing all images found.
Here is my solution in Python:
pmpa.py
:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import os 5 from os.path import abspath, expanduser, join, splitext, relpath 6 7 IMG = ".jpg .jpeg .png .gif".split() 8 9 HEADER = r"""<!DOCTYPE html> 10 <html> 11 <head> 12 <title>{title}</title> 13 <style type="text/css"> 14 {css} 15 </style> 16 </head> 17 <body> 18 """ 19 20 FOOTER = r""" 21 </body> 22 </html> 23 """ 24 25 CSS = r""" 26 img { 27 width: 30%; 28 border: 1px lavender solid; 29 } 30 """ 31 32 HEADLINE = '<h1>{0}</h1>' 33 DIR = '<h2><a href="{href}">{dirname}</a></h2>' 34 35 HR = '<hr />' 36 37 A_TAG = '<a href="{href}" title="{title}"><img src="{src}" alt="{alt}" /></a>' 38 39 def gen_html(root=None, absolute_path=True): 40 cwd = os.getcwd() 41 root = expanduser(root) if root else cwd 42 path_func = abspath if absolute_path else lambda p: relpath(p, cwd) 43 44 title = 'All images in ' + root 45 print(HEADER.format(title=title, css=CSS)) 46 print(HEADLINE.format(title)) 47 48 for dirpath, dirnames, filenames in os.walk(root): 49 path = path_func(dirpath) 50 print(HR) 51 print(DIR.format(href=path, dirname=path)) 52 53 for file in filenames: 54 name, ext = os.path.splitext(file) 55 if ext in IMG: 56 path = path_func(join(dirpath, file)) 57 print(A_TAG.format(href=path, title=path, src=path, alt=name)) 58 59 print(FOOTER) 60 61 if __name__ == '__main__': 62 gen_html()