Skip to content

Instantly share code, notes, and snippets.

@apsun
Last active March 6, 2022 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apsun/1246612e00294e78f4d128c1618fa72d to your computer and use it in GitHub Desktop.
Save apsun/1246612e00294e78f4d128c1618fa72d to your computer and use it in GitHub Desktop.
Normalize ID3 tags from filename
#!/usr/bin/env python3
import re
import os
import sys
import mutagen.id3
def main(filepath):
print(filepath)
# Save original mtime
stat = os.stat(filepath)
# Parse artist/title from filename
filename = os.path.basename(filepath)
match = re.match("(.*) - (.*).mp3", filename)
if not match:
raise RuntimeError("Filename not in `<artist> - <title>.mp3` format")
artist = match.group(1)
title = match.group(2)
# Load ID3 tags from file
try:
id3 = mutagen.id3.ID3(filepath)
except mutagen.id3.ID3NoHeaderError:
id3 = mutagen.id3.ID3()
# Clear all current ID3 tags
id3.delete(filepath)
# Add artist/title tags
id3.add(mutagen.id3.TPE1(encoding=mutagen.id3.Encoding.UTF8, text=[artist]))
id3.add(mutagen.id3.TIT2(encoding=mutagen.id3.Encoding.UTF8, text=[title]))
# Write ID3 tags to file, deleting ID3v1 tags
id3.save(filepath, v1=0)
# Restore original mtime
os.utime(filepath, times=(stat.st_atime, stat.st_mtime))
if __name__ == "__main__":
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
main(arg)
else:
for f in os.listdir():
if f.endswith(".mp3"):
main(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment