Skip to main content

Parse and manage posts with YAML (or other) frontmatter

Project description

Python Frontmatter

Jekyll-style YAML front matter offers a useful way to add arbitrary, structured metadata to text documents, regardless of type.

This is a small package to load and parse files (or just text) with YAML front matter.

Build Status

Install:

pip install python-frontmatter

Usage:

>>> import frontmatter

Load a post from a filename:

>>> post = frontmatter.load('tests/hello-world.markdown')

Or a file (or file-like object):

>>> with open('tests/hello-world.markdown') as f:
...     post = frontmatter.load(f)

Or load from text:

>>> with open('tests/hello-world.markdown') as f:
...     post = frontmatter.loads(f.read())

Access content:

>>> print(post.content)
Well, hello there, world.

# this works, too
>>> print(post)
Well, hello there, world.

Use metadata (metadata gets proxied as post keys):

>>> print(post['title'])
Hello, world!

Metadata is a dictionary, with some handy proxies:

>>> sorted(post.keys())
['layout', 'title']

>>> from pprint import pprint
>>> post['excerpt'] = 'tl;dr'
>>> pprint(post.metadata)
{'excerpt': 'tl;dr', 'layout': 'post', 'title': 'Hello, world!'}

If you don't need the whole post object, just parse:

>>> with open('tests/hello-world.markdown') as f:
...     metadata, content = frontmatter.parse(f.read())
>>> print(metadata['title'])
Hello, world!

Write back to plain text, too:

>>> print(frontmatter.dumps(post)) # doctest: +NORMALIZE_WHITESPACE
---
excerpt: tl;dr
layout: post
title: Hello, world!
---
Well, hello there, world.

Or write to a file (or file-like object):

>>> from io import BytesIO
>>> f = BytesIO()
>>> frontmatter.dump(post, f)
>>> print(f.getvalue().decode('utf-8')) # doctest: +NORMALIZE_WHITESPACE
---
excerpt: tl;dr
layout: post
title: Hello, world!
---
Well, hello there, world.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for python-frontmatter, version 0.5.0
Filename, size File type Python version Upload date Hashes
Filename, size python_frontmatter-0.5.0-py3-none-any.whl (8.4 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size python-frontmatter-0.5.0.tar.gz (9.1 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page