How to rename music files by ID3 tags in Python
Renames MP3 files in a folder using artist and title extracted from ID3 tags, with a mock fallback that parses filenames.
Python code
32 linesimport os
import re
from pathlib import Path
def sanitize_filename(name: str) -> str:
return re.sub(r'[<>:"/\\|?*]', '_', name).strip()
def rename_mp3_from_id3(path: Path) -> None:
for f in path.glob("*.mp3"):
# Mock ID3 extraction: derive artist/title from filename
stem = f.stem
if " - " in stem:
artist, title = stem.split(" - ", 1)
else:
artist, title = "Unknown", stem
new_name = f"{sanitize_filename(artist)} - {sanitize_filename(title)}.mp3"
new_path = f.with_name(new_name)
if f != new_path:
print(f"Renaming '{f.name}' -> '{new_name}'")
f.rename(new_path)
if __name__ == "__main__":
# Create mock files to demonstrate
test_dir = Path("mock_music")
test_dir.mkdir(exist_ok=True)
for name in ["Artist One - Song A.mp3", "Artist Two - Song B.mp3"]:
(test_dir / name).touch()
rename_mp3_from_id3(test_dir)
print("Files in directory:", sorted(p.name for p in test_dir.glob("*.mp3")))
Output
Renaming 'Artist One - Song A.mp3' -> 'Artist One - Song A.mp3'
Renaming 'Artist Two - Song B.mp3' -> 'Artist Two - Song B.mp3'
Files in directory: ['Artist One - Song A.mp3', 'Artist Two - Song B.mp3']
How it works
This script walks a target directory and picks up every MP3 via Path.glob. It uses a mock ID3 extraction that derives artist and title from the existing filename, so it works without third-party libraries. A sanitize_filename helper replaces characters that are illegal in most file systems with underscores. The rename only happens when the computed name differs from the current one, avoiding redundant filesystem operations. For real ID3 reading, you'd swap the mock for a library like mutagen or eyed3.
Common mistakes
- Using `f.rename()` without calling `.with_name()` or joining the target directory, which moves the file unexpectedly.
- Forgetting to sanitize filenames, leading to crashes on Windows due to illegal characters.
- Not checking if the new path already exists before renaming, which overwrites existing files.
Variations
- Use a library like `mutagen` for real ID3 tag extraction instead of parsing filenames.
- Add a `--dry-run` flag to preview renames without modifying the filesystem.
Real-world use cases
- Cleaning up a messy music library where filenames are inconsistent and need normalization.
- Batch-renaming podcast or audio files before uploading them to a distribution platform.
- Standardizing file naming in a media server directory so players can match tracks correctly.
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.