Skip to content

Instantly share code, notes, and snippets.

@hsandt
Created December 28, 2018 18:43
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 hsandt/b04bc6b680e672b1b23401b403bfa970 to your computer and use it in GitHub Desktop.
Save hsandt/b04bc6b680e672b1b23401b403bfa970 to your computer and use it in GitHub Desktop.
A simple Python script that sets the track number of all (supposedly) audio files found in folder "tracks" based on their respective names
#!/usr/bin env python3
# This is a very simple gist based on
# https://stackoverflow.com/questions/8948/accessing-mp3-meta-data-with-python/34970600#34970600
# to add track number metadata to music when the tracks are formatted as "{track_number}_Title.mp3"
# but the track number is missing in metadata.
# This script doesn't check that the file is an mp3, only that the file starts with a number.
# If you need another separator than '_', replace it directly in the script or add a parameter "separator"
# that you would pass to the script.
# This script changes metadata for any file matching this pattern, use with caution.
import os
from mutagen.easyid3 import EasyID3
def set_track_to_prefix_number():
"""
Walk over all files in "tracks" folder and set their audio tag "tracknumber" to
"{track_number}/{max_track_number}" where:
- track_number is extracted from the beginning
of the filename (e.g. 23 for a file named 23_My_Dearest.mp3)
- max_track_number is the total number of files in the current subfolder
(not in the whole "tracks" folder)
"""
for path, children_dirs, files in os.walk("tracks"):
max_track_number = len(files)
for file in files:
track_number = file.split("_")[0]
if not str.isdigit(track_number):
print(f"{file} does not start with '[integer]_', skip")
continue
audio = EasyID3(os.path.join(path, file))
audio['tracknumber'] = f"{track_number}/{max_track_number}"
audio.save()
print(f"Set tracknumber for {audio['tracknumber']}")
if __name__ == '__main__':
set_track_to_prefix_number()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment