Archive

Posts Tagged ‘html generator’

Static HTML filelist generator

March 26, 2011 1 comment

Problem

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.

Solution

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>
<body>
<code>
""",

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

    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):
        self.print_html_header()
        os.path.walk( self.base_dir, self.processDirectory, None )
        self.print_html_footer()

# class SimpleHtmlFilelistGenerator

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

Usage:

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).

Demo:

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/.

Design a site like this with WordPress.com
Get started