eyeseast / python-frontmatter

Parse and manage posts with YAML (or other) frontmatter
http://python-frontmatter.rtfd.io
MIT License
333 stars 42 forks source link

Is it possible to create a file with front matter and content? #71

Closed wsw70 closed 3 years ago

wsw70 commented 3 years ago

I have successfully read and parsed files with front matter and content.

I now would like to create one from scratch (provide entries for the frontmatter and a content. Is this possible?

I see it is possible to write back a file read with frontmatter, but I did not see the "from scratch" version in the docs.

eyeseast commented 3 years ago

You can use frontmatter.Post directly, if you want. You can also use any object that has content and metadata properties, where content is a string and metadata is a dictionary.

import frontmatter

p = frontmatter.Post("This is some content", title="My post")
frontmatter.dumps(p)

More here: https://python-frontmatter.readthedocs.io/en/latest/api.html#post-objects

wsw70 commented 3 years ago

Thank you @eyeseast .

I tried exactly this but for a reason it failed. Thinkng that it cannot be done, I ended up with a workaround (below is a shortened version to highlight the workaround):

def create():
    # read template
    f = io.StringIO("---\n---")
    note = frontmatter.load(f)
    filename = f"{uuid.uuid4().hex}.note"
    with open(filename, 'wb') as f:
        frontmatter.dump(note, f)

I will therefore try again, thanks!