Build an M3U Playlist from Folder MP3s in Python
Scans a folder for MP3 files and writes a valid M3U playlist with absolute file URIs.
Python code
33 linesfrom pathlib import Path
import sys
def build_playlist(folder: str, output: str = "playlist.m3u") -> str:
folder_path = Path(folder)
if not folder_path.is_dir():
raise FileNotFoundError(f"Folder not found: {folder}")
mp3_files = sorted(folder_path.glob("*.mp3"))
if not mp3_files:
print("No MP3 files found in the folder.")
return ""
lines = ["#EXTM3U"]
for mp3 in mp3_files:
lines.append(f"#EXTINF:-1,{mp3.stem}")
lines.append(mp3.resolve().as_uri())
playlist_path = folder_path / output
playlist_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
return str(playlist_path)
if __name__ == "__main__":
if len(sys.argv) > 1:
folder_input = sys.argv[1]
else:
folder_input = "."
result = build_playlist(folder_input)
if result:
print(f"Playlist created: {result}")
Output
$ python build_playlist.py /home/user/music
Playlist created: /home/user/music/playlist.m3u
$ cat /home/user/music/playlist.m3u
#EXTM3U
#EXTINF:-1,Song1
file:///home/user/music/Song1.mp3
#EXTINF:-1,Song2
file:///home/user/music/Song2.mp3
#EXTINF:-1,Song3
file:///home/user/music/Song3.mp3
How it works
The script uses pathlib.Path.glob("*.mp3") to collect MP3 files, sorted alphabetically for deterministic output. mp3.resolve().as_uri() creates a portable file:// URI that media players accept. Each track gets an #EXTINF line with a duration of -1 (unknown) and the title derived from the filename. The playlist is written as UTF-8 text with proper line endings, and the function returns the output path or an empty string when no MP3s are found.
Common mistakes
- Using forward slashes in paths without converting to URI format
- Forgetting to sort files, resulting in nondeterministic playlist order
- Hardcoding a fixed output path instead of writing next to the music folder
Variations
- Use `folder_path.rglob("*.mp3")` to include MP3s in subfolders
- Parse ID3 tags instead of filenames using mutagen for real track titles
Real-world use cases
- Generating playlists for embedded media players or car stereos that read M3U files from USB drives.
- Automating music library exports so DJ software can load the same track list across different machines.
- Creating daily radio-style playlists for office streaming systems by scanning a shared network folder.
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.