Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
# 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")
audio = EasyID3(os.path.join(path, file))
audio['tracknumber'] = f"{track_number}/{max_track_number}"
print(f"Set tracknumber for {audio['tracknumber']}")
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.