Convert Markdown (.md) to HTML using Python

In this tutorial, I will show you how to convert markdown to HTML using Python with just a few lines of code.

The Python package that I am going to use is: markdown.

I want to make this tutorial clean and simple so I will first show you with a simple input and output.

At the end of this tutorial, I have shown how you can do this in just 2 lines of Python code.

Convert Markdown string to HTML using Python’s markdown package

At first, you need to install markdownpackage. We can do this using any of the below commands:

pip3 install markdown
pip install markdown

If you are using terminal and facing issues with the above commands, you can try this one:

sudo apt update

and then

sudo apt install python3-markdown
import markdown

# Sample markdown text
sample_markdown_string = """
# Hello, I am Saruque from CodeSpeedy!

This is a sample markdown text.

- Markdown
-  to
- HTML

**This will be bold** and *and this is inside <em>*
"""

# Convert markdown to HTML
html_string = markdown.markdown(sample_markdown_string)

# Printing the result
print(html_string)

Output:

<h1>Hello, I am Saruque from CodeSpeedy!</h1>
<p>This is a sample markdown text.</p>
<ul>
<li>Markdown</li>
<li>to</li>
<li>HTML</li>
</ul>
<p><strong>This will be bold</strong> and <em>and this is inside <em></em></p>

Save the markdown to HTML result as a file

Now it’s time to save the file instead of printing it. If you require to save the file you can add the below lines to your previous code:

with open("output.html", "w") as f:
    f.write(html_string)

Now, if you run the program, it will save the converted HTML result in a .html file.

If you want to save the file as .txt you can simply change the output.html to output.txt.

Till now I have only shown you taking markdown input as a string, now I will show you how you can take markdown input from the actual .md file.

import markdown

with open("input.md", "r") as file:
    markdown_text = file.read()

html = markdown.markdown(markdown_text)

with open("output.html", "w") as output_file:
    output_file.write(html)

print("Markdown has been successfully converted to HTML and saved as output.html.")

If you run this Python code, it will save the result in your output file.

Make sure you write the md content in the input.md file.

Convert markdown to HTML in Python in 2 lines of code:

import markdown

markdown.markdownFromFile(input="input.md", output="output.html")

Using this trick, you can do the task in two lines.

Leave a Reply

Your email address will not be published. Required fields are marked *