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 (or JSON, TOML or other) front matter.
pip install python-frontmatter >>>importfrontmatterLoad a post from a filename:
>>>post=frontmatter.load('tests/yaml/hello-world.txt')Or a file (or file-like object):
>>>withopen('tests/yaml/hello-world.txt') asf: ... post=frontmatter.load(f)Or load from text:
>>>withopen('tests/yaml/hello-world.txt') asf: ... post=frontmatter.loads(f.read())If the file has a Byte-Order Mark (BOM), strip it off first. An easy way to do this is by using the utf-8-sig encoding:
>>>withopen('tests/yaml/hello-world.txt', encoding="utf-8-sig") asf: ... post=frontmatter.load(f)Access content:
>>>print(post.content) Well, hellothere, world. # this works, too>>>print(post) Well, hellothere, 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'] >>>frompprintimportpprint>>>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:
>>>withopen('tests/yaml/hello-world.txt') asf: ... 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;drlayout: posttitle: Hello, world! ---Well, hellothere, world.Or write to a file (or file-like object):
>>>fromioimportStringIO>>>f=StringIO() >>>frontmatter.dump(post, f) >>>print(f.getvalue()) # doctest: +NORMALIZE_WHITESPACE---excerpt: tl;drlayout: posttitle: Hello, world! ---Well, hellothere, world.For more examples, see files in the tests/ directory. Each sample file has a corresponding .result.json file showing the expected parsed output. See also the examples/ directory, which covers more ways to customize input and output.