Organize MkDocs Blog Posts with Python

Managing Markdown posts and their accompanying images can become chaotic fast. I wanted a repeatable, automated way to clean up my blog drafts and assets before publishing them to eirros.playground. Instead of sorting files manually, I built a Python script that organizes posts and assets into the right folder structure based on frontmatter metadata.
This guide documents how the script works and how I use it in my daily MkDocs workflow.
Folder Structure¶
Here’s the desired end result after organization:
docs/posts/2025/your-post-slug/your-post-slug.md
docs/posts/2025/your-post-slug/assets/your-post-slug-hero.png
Every post lives in its own subfolder under the correct year, and any assets (images, screenshots, etc.) are placed in an assets/ subdirectory right beside the .md file. This makes each post self-contained and easy to move, version, or delete.
How It Works¶
The script does the following:
- Scans the
raw_posts/folder for Markdown files - Reads the
date:from each post’s frontmatter to determine the year - Uses the filename (minus
.md) as the post slug - Injects the
slug:into frontmatter if it’s missing - Moves the
.mdfile and any matching assets to their final home - Warns about missing images or invalid frontmatter
- Logs everything in a timestamped file
All of this happens when I run:
You can place Markdown drafts in raw_posts/ and drop related images into raw_posts/assets/ with filenames that start with the same slug.
Requirements¶
This script is lightweight. You just need:
Also, make sure your project has this base directory structure:
mkdocs/
├── raw_posts/
│ ├── my-guide.md
│ └── assets/
│ └── my-guide-image.png
├── scripts/
│ └── organize_posts.py
├── docs/
│ └── posts/
Logs are stored in scripts/logs/ and old logs are rotated automatically.
What Counts as a Valid Post?¶
To be processed, a post must:
- Be a
.mdfile - Contain a valid
date:in frontmatter (e.g.2024-12-03)
If the post is missing a date, the script skips it and logs a warning.
Assets are matched by filename prefix. For example, a post called cool-feature.md will collect any images like:
cool-feature-hero.pngcool-feature-1.jpgcool-feature-diagram.svg
Slug Injection¶
Many of my older posts didn’t have slug: in frontmatter, which caused issues in routing. The script auto-injects it if missing, just before the closing --- of the YAML frontmatter.
This makes it safe to use in MkDocs or blog plugins that rely on slugs.
Inside the Script¶
Let’s break down some of the logic behind the scenes.
- extract_date_from_frontmatter(): Uses regex to find the
date:line in the frontmatter. This is what determines the year the post belongs to. - has_slug_frontmatter(): Checks if
slug:already exists. - inject_or_update_frontmatter(): If not, it inserts
slug:before the end of the YAML block. - copy_assets(): Moves any files from
raw_posts/assets/that start with the slug. It ensures assets are bundled with the post. - find_missing_assets_in_markdown(): Validates that all image links in the Markdown are actually present in the new
assets/folder. It catches broken links before publishing. - log_block(): Logs each action with color-coded output on terminal and also writes to a text log. I use this a lot when debugging drafts or checking asset misplacements.
- rotate_logs(): Keeps things clean by only keeping the last 30 log files.
This script is procedural by design—easy to follow, transparent, and ideal for small static sites.
Sample Log Output¶
Each time you run the script, a detailed log is created like:
=============================================
MkDocs Blog Post Organizer Log
Timestamp: 20180319-014947
=============================================
[01:49:47] [INFO]: docs/posts/2018/altaro-v7-backup-restore-guides/
• Post moved: altaro-v7-backup-restore-guides.md
• Asset moved: altaro-v7-backup-restore-guides-installation.png
• Asset moved: altaro-v7-backup-restore-guides-full-restore.png
---
Summary:
Total posts organized : 1
Posts with assets : 1
Posts without assets : 0
Total assets moved : 2
Skipped (already exist) : 0
Invalid posts : 0
Fail read file : 0
I usually tail this log while working to make sure nothing is skipped or misplaced.
Tips and Gotchas¶
- Avoid spaces or weird characters in filenames
- Ensure each Markdown post has a proper date
- Use consistent slug naming so asset matching works
- You can re-run the script safely; it skips files that already exist in destination
Full Python Script¶
Click to expand the full organize_posts.py script
"""
==================================================
MkDocs Blog Post Organizer for eirros.playground
==================================================
Automates the organization of Markdown blog posts and assets
into the following structure:
docs/posts/YYYY/your-post-slug/your-post-slug.md
docs/posts/YYYY/your-post-slug/assets/your-post-slug-*.png
Requirements:
- pip install python-slugify
Usage:
- Place .md files in raw_posts/
- Place related images in raw_posts/assets/ (must prefix match slug)
- Activate venv: source .venv/bin/activate
- Run from mkdocs/ root: python3 scripts/organize_posts.py
Features:
- Reads `date:` from frontmatter to determine year
- Uses filename (without extension) as slug
- Injects slug into frontmatter if missing
- Moves .md and assets into nested folder structure
- Logs actions in scripts/logs/
- Warns if no assets found or linked image missing
- Keeps max 30 logs
Log Format:
scripts/logs/organize_posts_<timestamp>.log
"""
import os
import re
import shutil
from pathlib import Path
from datetime import datetime
# ====== CONFIG ======
SOURCE_MD_DIR = "raw_posts"
SOURCE_ASSETS_DIR = "raw_posts/assets"
DEST_BASE = Path("docs/posts")
LOG_DIR = Path("scripts/logs")
MAX_LOGS = 30
DEFAULT_DESC = "Coming soon..."
# ====================
# ====== COLOR CODES ======
BLUE = "\033[94m"
YELLOW = "\033[93m"
RED = "\033[91m"
RESET = "\033[0m"
# =========================
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
log_file = LOG_DIR / f"organize_posts_{timestamp}.log"
LOG_DIR.mkdir(parents=True, exist_ok=True)
# Create and write log file header
with open(log_file, "a", encoding="utf-8") as f:
f.write("=============================================\n")
f.write(" 🧹 MkDocs Blog Post Organizer Log\n")
f.write(f" Timestamp: {timestamp}\n")
f.write("=============================================\n\n")
# Counters
total_posts = 0
posts_with_assets = 0
posts_without_assets = 0
skipped_posts = 0
invalid_posts = 0
failed_reads = 0
total_assets_moved = 0
def log_block(level, folder, messages, color=None):
ts = datetime.now().strftime("%H:%M:%S")
header = f"[{ts}] [{level.upper():<4}]: {folder}"
if color:
print(color + header + RESET)
else:
print(header)
for msg in messages:
print(f" • {msg}")
with open(log_file, "a", encoding="utf-8") as f:
f.write(header + "\n")
for msg in messages:
f.write(f" • {msg}\n")
f.write("\n")
def rotate_logs():
logs = sorted(LOG_DIR.glob("organize_posts_*.log"), key=os.path.getmtime)
if len(logs) > MAX_LOGS:
to_delete = logs[:len(logs) - MAX_LOGS]
for file in to_delete:
file.unlink()
print(f"[ROTATE] Deleted old log: {file.name}")
def extract_date_from_frontmatter(content):
match = re.search(r"^date:\s+(\d{4}-\d{2}-\d{2})", content, re.MULTILINE)
return match.group(1) if match else None
def has_slug_frontmatter(content):
return bool(re.search(r"^slug:\s+", content, re.MULTILINE))
def inject_or_update_frontmatter(content, slug):
if has_slug_frontmatter(content):
return content
lines = content.strip().splitlines()
output = []
in_frontmatter = False
inserted = False
for line in lines:
output.append(line)
if line.strip() == "---":
if in_frontmatter and not inserted:
output.insert(-1, f"slug: {slug}")
inserted = True
in_frontmatter = not in_frontmatter
return "\n".join(output)
def copy_assets(slug, asset_dest):
asset_dest.mkdir(parents=True, exist_ok=True)
matched_files = [f for f in os.listdir(SOURCE_ASSETS_DIR) if f.startswith(slug)]
moved = []
for f in matched_files:
src = os.path.join(SOURCE_ASSETS_DIR, f)
dst = os.path.join(asset_dest, f)
if os.path.exists(src):
shutil.move(src, dst)
moved.append(f)
return moved
def find_missing_assets_in_markdown(content, asset_folder):
linked_assets = re.findall(r'\]\(\.\/assets\/([^)]+)\)', content)
return [name for name in linked_assets if not (asset_folder / name).exists()]
def organize_posts():
global total_posts, posts_with_assets, posts_without_assets
global skipped_posts, invalid_posts, failed_reads, total_assets_moved
for file in os.listdir(SOURCE_MD_DIR):
if not file.endswith(".md"):
continue
slug = Path(file).stem
source_path = os.path.join(SOURCE_MD_DIR, file)
messages = []
try:
with open(source_path, "r", encoding="utf-8") as f:
content = f.read()
except Exception:
log_block("FAIL", f"{DEST_BASE}/????/{slug}/", ["Fail read file", "Fail read file"], RED)
failed_reads += 1
continue
date = extract_date_from_frontmatter(content)
if not date:
log_block("WARN", f"{DEST_BASE}/????/{slug}/", ["Invalid posts", "Assets found but not moving due to invalid posts"], YELLOW)
invalid_posts += 1
continue
year = date.split("-")[0]
post_folder = DEST_BASE / year / slug
post_folder.mkdir(parents=True, exist_ok=True)
dest_md_path = post_folder / f"{slug}.md"
if dest_md_path.exists():
log_block("INFO", str(post_folder) + "/", [f"Skipped (already exists): {dest_md_path.name}"], YELLOW)
skipped_posts += 1
continue
final_content = inject_or_update_frontmatter(content, slug)
with open(dest_md_path, "w", encoding="utf-8") as f:
f.write(final_content)
os.remove(source_path)
messages.append(f"📝 Post moved: {dest_md_path.name}")
asset_folder = post_folder / "assets"
assets = copy_assets(slug, asset_folder)
if assets:
for a in assets:
messages.append(f"🎨 Asset moved: {a}")
total_assets_moved += len(assets)
posts_with_assets += 1
else:
messages.append(f"💀 No assets found for slug: {slug}")
posts_without_assets += 1
# Validate image links in Markdown
missing = find_missing_assets_in_markdown(final_content, asset_folder)
if missing:
for m in missing:
messages.append(f"⚠️ Linked but missing: {m}")
log_block("INFO", str(post_folder) + "/", messages, BLUE)
total_posts += 1
final_time = datetime.now().strftime("%H:%M:%S")
print(f"[{final_time}] Finished organizing {total_posts} post(s), {total_assets_moved} asset(s) moved\n")
print("---\nSummary:")
print(f"Total posts organized : {total_posts}")
print(f"Posts with assets : {posts_with_assets}")
print(f"Posts without assets : {posts_without_assets}")
print(f"Total assets moved : {total_assets_moved}")
print(f"Skipped (already exist) : {skipped_posts}")
print(f"Invalid posts : {invalid_posts}")
print(f"Fail read file : {failed_reads}\n")
with open(log_file, "a", encoding="utf-8") as f:
f.write(f"[{final_time}] Finished organizing {total_posts} post(s), {total_assets_moved} asset(s) moved\n\n")
f.write("---\nSummary:\n")
f.write(f"Total posts organized : {total_posts}\n")
f.write(f"Posts with assets : {posts_with_assets}\n")
f.write(f"Posts without assets : {posts_without_assets}\n")
f.write(f"Total assets moved : {total_assets_moved}\n")
f.write(f"Skipped (already exist) : {skipped_posts}\n")
f.write(f"Invalid posts : {invalid_posts}\n")
f.write(f"Fail read file : {failed_reads}\n")
rotate_logs()
if __name__ == "__main__":
organize_posts()
View script on GitHub
Conclusion¶
This script has saved me hours of manual sorting and makes it super easy to maintain a clean, consistent folder structure for my MkDocs blog. It’s also one of those quiet helpers that keeps things tidy without fanfare.
If you’re also dealing with Markdown chaos, automate it. You’ll thank yourself later.
For full source and updates, check the GitHub repo or the scripts/organize_posts.py file in this project.
Happy writing.