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 # # https://stackoverflow.com/questions/25697664/how-would-i-parse-front-matter-with-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 io.open(fname, 'r') as f: post = frontmatter.load(f) if post.get('author') == None: post['authors'] = auths newfile = io.open( fname, 'w', encoding='utf8') #frontmatter.dump(post, newfile) newfile.write ( frontmatter.dumps(post) ) newfile.close()
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!