It was a bright evening and the time was 18:30 IST , Kushal told “Let us write a bigger project part by part then,What about a static blog generator?” And I was like feeling like wow I’ll be making a static site generator like Jekyll by what I was thinking to host my site in github. Though the job is not easy enough because a static site generator can not be made overnight. But I was almost done with an Initial step to static site generator i.e, converting a markdown file to a html file.
Kushal introduced us with markdown2 module of Python3. Markdown2 belongs to pypi which is the official third-party software repository for Python Programming Language. Markdown2 is a text-to-html filter that converts plain text formatting to HTML which fulfills one of the most important features of a static site generator.
To install the package in fedora do sudo yum/dnf install python3-markdown2
The first problem given by Kushal was to write a program “Which will read a given markdown file, and generate a HTML file in a given path”.
And this did not take much time to solve
#!/usr/bin/env python3 from markdown2 import Markdown def generate_post(source, destination): with open(source, 'r') as s: smd = s.read() markdowner = Markdown() dest = markdowner.convert(smd) with open(destination, 'w') as h: h.write(dest)
After going through my code Kushal said, “Looks good”. And he shoot an another problem that took longer time to solve. He told to write a program “Which will search for .md (markdown) files in a given directory, and finally convert them into HTML files in another given directory”. Creating the HTML files in another directory was like hammering in my head .
I was almost done with the problem with some parsing issues. SanketDG helped me to solve the errors I was getting, so thanks to him 🙂 .
#!/usr/bin/env python3 from os import path from markdown2 import Markdown import os def generator_post(source, destination): with open(source, 'r') as s: smd = s.read() markdowner = Markdown() dest = markdowner.convert(smd) with open(destination, 'w') as h: h.write(dest) def convert_to_html(md_path,html_path): for f in os.listdir(md_path): if f.endswith('.md'): hname = os.path.splitext(f) + '.html' html_path2 = os.path.join(html_path, hname) generator_post(os.path.join(md_path, f), html_path2) if __name__ == '__main__': convert_to_html('dir_path1','dir_path2')