Skip to Content

Setting Hugo frontmatter using Python

Posted on One min read

Recently I switched the theme of my blog (based on hugo). My new theme is supporting some new features like authors. This feature requires some additional parameters in the front matter of the post. I found a very convenient way using the Python package front matter. The code below changes these parameters automatically. The original script was posted in a StackOverflow answer but doesn’t work for me. So I modified it slightly.

#!/usr/bin/env python
import frontmatter
import io 
from os.path import basename, splitext
import glob

auths = ['daniel']

path = "content/docs/*.md"

for fname in glob.glob(path):
    with, 'r') as f:
        post = frontmatter.load(f)

        if post.get('author') == None:
            post['authors'] = auths
            newfile = fname, 'w', encoding='utf8')
            #frontmatter.dump(post, newfile)
            newfile.write ( frontmatter.dumps(post) )

The script above checks the existence of authors in all markdown files inside the predefined path. Contains the post an existing parameter it does nothing, is it missing it will be added automatically. Very convenient!