Markdown is a popular format for writing content that’s easy to read and write, but converting it to HTML can be a hassle. In this post, I’ll show you how to create a simple Markdown to HTML converter using Python. This tool will allow you to convert your Markdown files into beautifully formatted HTML documents with just a few commands.
What You’ll Need
• Python: Make sure Python is installed on your system.
• Markdown Library: We’ll use the markdown library to handle the conversion.
Step-by-Step Guide
- Set Up Your Project
Create a new directory for your project and navigate into it:
mkdir markdown_to_html
cd markdown_to_html
- Install the Markdown Library
Install the markdown library using pip:
pip install markdown
- Create Your Python Script
Create a new file named md_to_html.py:
touch md_to_html.py
Open md_to_html.py and add the following code:
import markdown
import sys
def markdown_to_html(md_text):
"""Convert Markdown text to HTML."""
return markdown.markdown(md_text)
def main():
if len(sys.argv) != 3:
print("Usage: python md_to_html.py input.md output.html")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
try:
with open(input_file, 'r') as f:
md_text = f.read()
except FileNotFoundError:
print(f"Error: The file '{input_file}' does not exist.")
sys.exit(1)
html_text = markdown_to_html(md_text)
with open(output_file, 'w') as f:
f.write(html_text)
print(f"Converted '{input_file}' to '{output_file}'")
if __name__ == "__main__":
main()
- Run Your Converter
Save your script and run it from the terminal:
python md_to_html.py example.md example.html
Conclusion
With just a few lines of Python code, you’ve created a powerful tool to convert Markdown to HTML. This simple script can be customized and extended to fit more advanced needs, but it’s a solid start for anyone looking to streamline their Markdown-to-HTML workflow.
Happy coding!