Skip to content

[Python] Use “markdown” Package To Convert Markdown File To HTML Format

Markdown is a Lightweight Markup Language (LML), you can use very simple syntax to create a pretty note, so it has been welcomed by many programmers.

In the past, I used online tool to write markdown syntax, but today I need to convert many markdown files to html format. So I start to find any packages it can do that.

In the beginning I try to use package manager tool on Linux or Mac OS (such as APT and Homebrew), but I found they can not support Table.

Perhaps I did not find a suitable kit.

Finally, I discovered that there is a markdown package in Python, and the Table can be create successfully.


How to use markdown package in Python

First, you can use the following command to install:

pip3 install markdown


For testing, I created a test.md file.

# [H1] TITLE  
## [H2]  

- 01
- 02
- 03


|Name|Age|
|:--:|:-:|
|Clay|26|
|Atlas|25|


Then we can use the following program to convert the test.md file to HTML format. By the way, if there are any formats you can not converted, you can confirm the extensions from python markdown package (https://python-markdown.github.io/extensions/).

import markdown


def main():
    md_file = open('test.md', 'r').read()
    html = markdown.markdown(md_file, extensions=['tables'])
    print(html)

if __name__ == '__main__':
    main()


Output:

<h1>[H1] TITLE</h1>
<h2>[H2]</h2>
<ul>
<li>01</li>
<li>02</li>
<li>03</li>
</ul>
<table>
<thead>
<tr>
<th align="center">Name</th>
<th align="center">Age</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center">Clay</td>
<td align="center">26</td>
</tr>
<tr>
<td align="center">Atlas</td>
<td align="center">25</td>
</tr>
</tbody>
</table>


We open the web page, and we will find it’s done.

You might want to say: Where is the line?

But according to Issues 863 on GitHub, this is normal standard HTML output, and the developers seem to have no intention of changing it for the time being. So if you want to add the border or line of the table, don’t hesitate, modify by yourself!


References


Read More

Leave a Reply