Writing front matter using Python

Posted: | Tags: til

I use python-frontmatter to read and parse the front matter in Markdown files used on the main site. The front matter is used to set page or post titles, along with categories and tags. The python-frontmatter library provides ways to load a file and parse the front matter making it available as a dict. However, there isn’t a documented way to write1 the front matter content to files if you’re starting from a dict.2

The library does have a Post object which contains the front matter and content for a file. You can create a Post when with the details you need and then write the object to a file as a string.

In order to do this I created a dictionary called and assigned it to a post variable with all the metadata for the front matter and the variable content which contains the posts Markdown content as a string. Both variables are then used to create a Post object. The Post object is then passed into frontmatter.dump() along with a file name to create the file.

    content = "Just some random _content_."
    post = {}
    post["title"] = "Title of the post"
    post["slug"] = "hello-world"
    post["tags"] = ["blog", "test"]
    post["published"] = datetime.datetime.fromtimestamp(1721215525)

    post_obj = frontmatter.Post(content, **post)
    frontmatter.dump(post, f"./post/{post["slug"]}.md")

  1. The documentation does technically describe how to write a Post object to a file but doesn’t go further into showing how to create a Post without first reading from a file. ↩︎

  2. I needed to do this when migrating part of my content from SQLite to Markdown files. ↩︎


Related ramblings