Parsing Frontmatter with Python

Script to add frontmatter variables to an existing markdown file using the python-frontmatter package.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import frontmatter
from os.path import basename, splitext
import glob

path = "content/notes/hugo/*.md" # "**/*.md to include subdirectories"
key = "tags" # key to search for

for fname in glob.glob(path):
    with open(fname, encoding="utf8") as f:
        post = frontmatter.load(f)

        # If no tags exist, create one with the 'hugo' of hugo
        if post.get(key) == None:
            post[key] = 'hugo'
            print(post[key])
        else:  # tags exist
            cat = post[key]
            main = 'hugo'
            # If tags contains a single item, ex: tags: 'category1'
            if type(cat) == str:
                if cat.lower() != main:
                    cat = [cat, main]
            else:  # If tags is a list, ex: tags: [cat1, cat2]
                cat = [s.lower() for s in cat]
                if main not in cat:
                    cat.append(main)

            post[key] = cat
            print(post[key])

        # Save the file.
        newfile = open(fname, 'wb')
        frontmatter.dump(post, newfile)
        newfile.close()

Related