Convert Markdown to HTML in Python (Batch)
Convert every Markdown file in a directory to HTML with the Python markdown library, saving each result with an .html extension.
pip install markdown
Python code
35 linesimport markdown
from pathlib import Path
def convert_md_to_html(source_dir: str, dest_dir: str) -> list[str]:
src = Path(source_dir)
dst = Path(dest_dir)
dst.mkdir(parents=True, exist_ok=True)
converted_files = []
for md_file in src.glob("*.md"):
html_content = markdown.markdown(md_file.read_text(encoding="utf-8"))
html_file = dst / md_file.with_suffix(".html").name
html_file.write_text(html_content, encoding="utf-8")
converted_files.append(html_file.name)
return converted_files
if __name__ == "__main__":
from tempfile import TemporaryDirectory
with TemporaryDirectory() as temp_dir:
src = Path(temp_dir) / "markdown"
dst = Path(temp_dir) / "html"
src.mkdir()
(src / "intro.md").write_text("# Hello World\n\nThis is **bold** text.", encoding="utf-8")
(src / "notes.md").write_text("## Section\n\n- Item 1\n- Item 2", encoding="utf-8")
results = convert_md_to_html(src, dst)
for filename in sorted(results):
print(f"=== {filename} ===")
print((dst / filename).read_text(encoding="utf-8"))
Output
=== intro.html ===
<h1>Hello World</h1>
<p>This is <strong>bold</strong> text.</p>
=== notes.html ===
<h2>Section</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
How it works
The markdown.markdown() function parses a Markdown string and returns the equivalent HTML. We iterate over *.md files in the source directory using Path.glob, read each file as UTF-8 text, and write the converted HTML to a new file with an .html suffix. The destination directory is created upfront with mkdir(parents=True, exist_ok=True), so the script works even if it doesn't exist. The function returns a list of the generated HTML filenames for easy reporting.
Common mistakes
- Forgetting to install the `markdown` package with `pip install markdown`.
- Reading files without `encoding='utf-8'`, causing UnicodeDecodeError on non-ASCII content.
- Writing HTML to the same filename as the Markdown file, overwriting the source.
- Assuming the destination directory exists — use `mkdir` first.
Variations
- Use `src.rglob('*.md')` to process Markdown files in subdirectories too.
- Add `extensions=['tables', 'fenced_code']` to the `markdown.markdown` call for extras.
Real-world use cases
- Building a static site generator that turns Markdown documentation into HTML pages.
- Converting batches of README or guide files into a format ready for email or a CMS import.
- Automating report generation where analysts write Markdown and need HTML for a dashboard.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.