Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. import frontmatter
  2. from pathlib import Path
  3. import re
  4. import os
  5. import errno
  6.  
  7. p = Path("./posts")
  8.  
  9. for path in p.glob("*.markdown"):
  10. with open(path, mode="r", encoding="UTF-8") as f:
  11. lines = f.readlines()
  12. clean_lines = [l.strip() for l in lines if l.strip()]
  13. post = frontmatter.loads("\n".join(clean_lines))
  14.  
  15. # I don't need anything but "title" from the existing frontmatter
  16. for key in list(post.metadata):
  17. if key not in ("title"):
  18. del post.metadata[key]
  19.  
  20. # Add date from the old post title to the frontmatter
  21. match = re.match(r"([\d]{4}-[\d]{2}-[\d]{2})-{1}(.+)", path.stem)
  22. post["date"] = match.groups()[0]
  23.  
  24. slug = match.groups()[1]
  25.  
  26. filename = f"converted_posts/{slug}/index.markdown"
  27. if not os.path.exists(os.path.dirname(filename)):
  28. try:
  29. os.makedirs(os.path.dirname(filename))
  30. except OSError as exc: # Guard against race condition
  31. if exc.errno != errno.EEXIST:
  32. raise
  33.  
  34. with open(filename, mode="w") as of:
  35. of.write(frontmatter.dumps(post))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement