How I would parse "Front Matter" with Python

I cannot provide any examples of how to parse "Front Matter" with Python. I have the following:

---
name: David
password: dwewwsadas
email: david@domain.com
websiteName: Website Name
websitePrefix: websiteprefix
websiteDomain: domain.com
action: create
---

      

and I am using the following code:

listing = os.listdir(path)
for infile in listing:
    stream = open(os.path.join(path, infile), 'r')
    docs = yaml.load_all(stream)
    for doc in docs:
        for k,v in doc.items():
            print k, "->", v
    print "\n",

      

I keep getting errors because of the second set ---

+3


source to share


2 answers


I know this is an old question, but I ran into the same problem and used python-frontmatter

. Below is an example of adding a new variable to the Front element :

import frontmatter
import io
from os.path import basename, splitext
import glob

# Where are the files to modify
path = "en/*.markdown"

# Loop through all files
for fname in glob.glob(path):
    with io.open(fname, 'r') as f:
        # Parse file front matter
        post = frontmatter.load(f)
        if post.get('author') == None:
            post['author'] = "alex"
            # Save the modified file
            newfile = io.open(fname, 'w', encoding='utf8')
            frontmatter.dump(post, newfile)
            newfile.close()

      



Source : How to parse frontmatter with python

+3


source


---

launches new documents that leads to your second document is blank, and doc

- None

for the second part. You walk through key / value pairs doc

as if each doc

is Python dict

or an equivalent type, but None

not, so you have to check this inside your loop (there are, of course, several ways to do this and what to do if doc

it isn't dict

):



....
for doc in yaml.load_all(stream):
    if hasattr(doc, 'items'):
        for k, v in doc.items():
            print k, "->", v
    else:
        print doc

      

+2


source







All Articles