我似乎无法解释如何使用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",
由于第二组---
答案 0 :(得分:5)
我知道这是一个老问题,但我遇到了同样的问题并使用了python-frontmatter
。以下是向前端内容添加新变量的示例:
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()
答案 1 :(得分:2)
---
启动新文档,导致第二个文档为空,第二部分doc
为None
。您遍历doc
的键值对,就好像每个doc
都是Python dict
或等效类型,但None
不是,所以您应该测试在你的循环中(当然有多种方法可以做到这一点,以及doc
不是dict
时该怎么做):
....
for doc in yaml.load_all(stream):
if hasattr(doc, 'items'):
for k, v in doc.items():
print k, "->", v
else:
print doc