Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save magicwenli/eb60df291270cf3b298fbbb576993091 to your computer and use it in GitHub Desktop.
Save magicwenli/eb60df291270cf3b298fbbb576993091 to your computer and use it in GitHub Desktop.
ID3Tag your *.(mp3|flac) from filename
# origin code by hiryu85
# https://github.com/hiryu85/python-ID3TagFromFilename/blob/master/id3fromfile.py
# rewrite at 2022.06.04
from glob import glob
from re import match
from string import Template
from sys import argv, exit
from mutagen import File
ID3TagMap = {
'tracknumber': '(?P<trackNum>\d+)',
'title': '(?P<title>.+)',
'artist': '(?P<artist>.+)',
'album': '(?P<album>.+)',
}
if __name__ == '__main__':
if len(argv) < 2:
print('Usage: %s "pattern" <template>' % argv[0])
exit(1)
file_pattern, file_template = argv[1:]
print('Matching %s:' % file_pattern)
for fname in glob(file_pattern):
ftitle = ''.join(fname.rsplit('.', 1)[:-1])
print(fname + ' ...', end="")
try:
id3tag_regex_pattern = r'^%s$' % Template(file_template).substitute(ID3TagMap)
try:
id3tags = match(id3tag_regex_pattern, ftitle).groupdict([])
audiofile = File(fname)
try:
audiofile.add_tags()
except Exception:
pass
if len(audiofile.keys()) > 1:
print(" SKIPPED")
continue
for tag in id3tags.keys():
value = id3tags[tag]
audiofile[tag.upper()] = value
audiofile.save()
print(' [OK]')
except Exception as e:
print(repr(e))
pass
except ValueError:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment