如何解析';前沿问题';用Python

如何解析';前沿问题';用Python,python,yaml,Python,Yaml,我似乎找不到任何关于如何用Python解析“Front Matter”的例子。我有以下资料: --- name: David password: dwewwsadas email: david@domain.com websiteName: Website Name websitePrefix: websiteprefix websiteDomain: domain.com action: create --- 我使用的代码如下: listing = os.listdir(path) for

我似乎找不到任何关于如何用Python解析“Front Matter”的例子。我有以下资料:

---
name: David
password: dwewwsadas
email: david@domain.com
websiteName: Website Name
websitePrefix: websiteprefix
websiteDomain: domain.com
action: create
---
我使用的代码如下:

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",
由于第二组
--

--
启动新文档,导致您的第二个文档为空,第二部分的
doc
None
,因此我不断出现错误。您遍历
doc
的键、值对,就好像每个
doc
都是Python
dict
或等效类型,但
None
不是,所以您应该在循环中测试这一点(当然有多种方法可以做到这一点,如果
doc
不是
dict
,该怎么做):


我知道这是一个老问题,但我只是面对同样的问题,并使用了
pythonfrontment
。下面是一个将新变量添加到前端的示例:

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's 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()
来源

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's 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()