Convert All Markdown Files in a Folder to HTML in Python
Batch convert every .md file in a folder to .html using the `markdown` library with the 'extra' extensions.
pip install markdown
Python code
36 linesimport os
import markdown
from pathlib import Path
def convert_md_folder_to_html(input_folder="markdown_files", output_folder="html_pages"):
input_path = Path(input_folder)
output_path = Path(output_folder)
output_path.mkdir(exist_ok=True)
for md_file in input_path.glob("*.md"):
with open(md_file, "r", encoding="utf-8") as f:
md_content = f.read()
html_content = markdown.markdown(md_content, extensions=["extra"])
html_filename = md_file.stem + ".html"
html_filepath = output_path / html_filename
with open(html_filepath, "w", encoding="utf-8") as f:
f.write(html_content)
print(f"Converted: {md_file.name} -> {html_filepath}")
if __name__ == "__main__":
# Create sample markdown files for demonstration
sample_folder = Path("markdown_files")
sample_folder.mkdir(exist_ok=True)
(sample_folder / "hello.md").write_text("# Hello World\nThis is a test.")
(sample_folder / "example.md").write_text("## Example\n- Item 1\n- Item 2")
convert_md_folder_to_html()
# Show results
print("\nGenerated HTML files:")
for html_file in Path("html_pages").glob("*.html"):
print(f" {html_file.name}: {html_file.read_text()[:50]}...")
Output
Converted: hello.md -> html_pages/hello.html
Converted: example.md -> html_pages/example.html
Generated HTML files:
hello.html: <h1>Hello World</h1>
<p>This is a test.</p>...
example.html: <h2>Example</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>...
How it works
The script uses pathlib.Path for clean filesystem traversal and markdown.markdown() with the "extra" extension set, which enables tables, fenced code blocks, and other common Markdown features. It reads each .md file from the input directory, converts the content to HTML, and writes it to the output directory, creating the output folder if needed. The glob("*.md") pattern ensures only Markdown files are processed, and the stem attribute extracts the filename without extension for naming the output HTML.
Common mistakes
- Forgetting to install the `markdown` package via pip before running the script.
- Using `Path.glob('*.md')` without specifying an absolute or relative path that exists—if the folder is missing, the loop runs zero times silently.
- Not adding the `"extra"` extensions list, so advanced syntax like tables or code blocks won't render properly.
- Overwriting existing HTML files without warning—add a check if the output file already exists for safety.
Variations
- Use `mistune` or `python-markdownify` alternative libraries for Markdown-to-HTML conversion.
- Wrap the generated HTML with a template (e.g., `<html><body>...</body></html>`) for full page structures.
Real-world use cases
- Building static documentation sites where each Markdown doc becomes a standalone HTML page for offline browsing.
- Migrating knowledge base articles from GitHub wikis (Markdown) to a simple web server for internal team use.
- Automating the creation of HTML email templates or landing page content stored as Markdown files in a CMS.
Sponsored
More from Files & data
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Personal Work Hours Tracker in Python medium
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
Keep learning
Related tutorials and quizzes for this topic.