Home > python > Static HTML filelist generator

Static HTML filelist generator


On our webserver I had some files in a directory that I wanted to browse online. However, the webserver didn’t generate a list of links on these files when I pointed the browser to this directory.


Idea: write a script that traverses the current directory recursively and prints all files with a link to them. I didn’t need any fancy features so the script can produce a very simple output.

Download link: here. Source code:

#!/usr/bin/env python

# index_gen.py

import os
import os.path
import sys

class SimpleHtmlFilelistGenerator:
    # start from this directory
    base_dir = None

    def __init__(self, dir):
        self.base_dir = dir

    def print_html_header(self):
        print """<html>

    def print_html_footer(self):
        print """</code>

    def processDirectory ( self, args, dirname, filenames ):
        print '<strong>', dirname + '/', '</strong>', '<br>'
        for filename in sorted(filenames):
            rel_path = os.path.join(dirname, filename)
            if rel_path in [sys.argv[0], './index.html']:
                continue   # exclude this generator script and the generated index.html
            if os.path.isfile(rel_path):
                href = "<a href=\"%s\">%s</a>" % (rel_path, filename)
                print '&nbsp;' * 4, href, '<br>'

    def start(self):
        os.path.walk( self.base_dir, self.processDirectory, None )

# class SimpleHtmlFilelistGenerator

if __name__ == "__main__":
    base_dir = '.'
    if len(sys.argv) > 1:
        base_dir = sys.argv[1]
    gen = SimpleHtmlFilelistGenerator(base_dir)


Simply launch it in the directory where you need the filelist. Redirect the output to index.html:

./index_gen.py >index.html

Don’t forget to set the rights of index.html (chmod 644 index.html).


Update (20141202)
This version here works but it’s quite primitive. We made a much better version; check it out here: https://pythonadventures.wordpress.com/2014/12/02/static-html-file-browser-for-dropbox/.

  1. James Crofts
    July 3, 2011 at 16:35

    Just what I was looking for! Thanks.

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: