Python Frontmatter
Parse and manage posts with YAML (or other) frontmatter. This library simplifies reading and writing content files that include metadata blocks, typically used in static site generators or content management systems. Current version is 1.1.0. Releases are infrequent but stable, primarily focused on maintenance, Python version compatibility, and type hinting.
Warnings
- breaking Version 1.0.0 removed official support for Python 2.x, Python 3.4, and Python 3.5. Users on these older Python versions should stick to `python-frontmatter<1.0.0`.
- gotcha The `load()` function expects a file-like object (e.g., from `open()`), while `loads()` expects a string. Mixing them up is a common error.
- gotcha By default, `load` and `loads` parse frontmatter using the YAML format. If your content uses JSON or TOML frontmatter, you must explicitly provide the correct handler.
Install
-
pip install python-frontmatter
Imports
- load
from frontmatter import load
- loads
from frontmatter import loads
- dumps
from frontmatter import dumps
- Post
from frontmatter import Post
- Frontmatter
from frontmatter import Frontmatter
- YAMLHandler
from frontmatter.handlers import YAMLHandler
- JSONHandler
from frontmatter.handlers import JSONHandler
- TOMLHandler
from frontmatter.handlers import TOMLHandler
Quickstart
import frontmatter
# Example content with YAML frontmatter
content_string = '''---
title: My Awesome Post
author: John Doe
tags:
- python
- frontmatter
---
This is the *body* of my post.
It can contain anything.
'''
# Load from a string
post = frontmatter.loads(content_string)
print(f"Title: {post['title']}")
print(f"Author: {post.metadata.get('author')}")
print(f"Content:\n{post.content}")
# Modify the post
post['status'] = 'published'
post.metadata['tags'].append('documentation')
post.content = "New content! " + post.content
# Dump back to a string
modified_content = frontmatter.dumps(post)
print("\n--- Modified Content ---\n")
print(modified_content)
# Example using JSON handler
json_content_string = '''---
{\"title\": \"JSON Post\", \"lang\": \"en\"}
---
Body of JSON post.
'''
json_post = frontmatter.loads(json_content_string, handler=frontmatter.handlers.JSONHandler)
print(f"\nJSON Post Title: {json_post['title']}")