Notes

Creating and Viewing HTML Files with Python

Edit on GitHub


Python
2 minutes

Writing HTML is just writing a string to a .html file. Python gives you the file I/O; your string is the markup.

Writing an HTML file

1f = open('helloworld.html', 'w')
2
3message = """<html>
4<head></head>
5<body><p>Hello World!</p></body>
6</html>"""
7
8f.write(message)
9f.close()

'w' is write mode — creates a new file, overwrites if one exists. Other modes you’ll see: 'r' (read), 'a' (append).

Modern style uses a with block so the file closes automatically:

1with open('helloworld.html', 'w') as f:
2    f.write(message)

Opening it in a browser

Python’s stdlib has a webbrowser module that opens a URL (or a local file) in the default browser:

1import webbrowser
2webbrowser.open_new_tab('helloworld.html')

On macOS/Linux you may need the full file:// path for it to resolve:

1webbrowser.open_new_tab('file:///Users/foo/Desktop/helloworld.html')

Wrapping data as HTML

The point of generating HTML from Python is usually to dump data into a viewable file — a word frequency list, scrape results, a report. The recipe:

  1. Build the body as a string (concatenate, loop, join, or f-strings)
  2. Drop it into an HTML template
  3. Write to disk, open in browser
 1import datetime, webbrowser
 2
 3def wrap_html(program, url, body):
 4    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
 5    filename = f"{program}.html"
 6
 7    template = f"""<html>
 8    <head><title>{program} output - {now}</title></head>
 9    <body>
10      <p>URL: <a href="{url}">{url}</a></p>
11      <p>{body}</p>
12    </body>
13    </html>"""
14
15    with open(filename, 'w') as f:
16        f.write(template)
17
18    webbrowser.open_new_tab(filename)

Usage — e.g. dumping a word frequency list:

1body = ""
2for word, count in sorted_freq:
3    body += f"{word}: {count}<br />"
4
5wrap_html("word-freq", "http://example.com/source", body)

The original lessons use %s string interpolation (frame % 'banana'). f-strings (Python 3.6+) are the modern equivalent and read more cleanly.

Related