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.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 14 views 0 copies

Requires third-party packages — install first
pip install markdown

Python code

35 lines
Python 3.9+
import 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

stdout
=== 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

  1. Use `src.rglob('*.md')` to process Markdown files in subdirectories too.
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Automation & scripting

Related tutorials and quizzes for this topic.