Add track number to song file name
Jump to navigation
Jump to search
This is a script that will auto-rename the songs in an album to show the track number.
Navigate to the songs and run it to go from this:
Caipirinha (feat. Bebel Gilberto).mp3
Celebrity Death Match (feat. Kid Koala).mp3
Don't Even Trip (feat. Amon Tobin).mp3
Five Seconds (feat. Odd Nosdam).mp3
Getaway (feat. Kool Keith).mp3
How U Feelin (feat. Doseone).mp3
Kill the DJ (feat. Massive Attack).mp3
Mojo (feat. Rahzel and Dan the Automator).mp3
Sucker (feat. Norah Jones).mp3
We're Not Alone (remix) (feat. Dub Trio).mp3
Your Neighborhood Spaceman (feat. Jel and Odd Nosdam).mp3
To this:
01 - Five Seconds (feat. Odd Nosdam).mp3
02 - Mojo (feat. Rahzel and Dan the Automator).mp3
03 - Don't Even Trip (feat. Amon Tobin).mp3
04 - Getaway (feat. Kool Keith).mp3
05 - Your Neighborhood Spaceman (feat. Jel and Odd Nosdam).mp3
06 - Kill the DJ (feat. Massive Attack).mp3
07 - Caipirinha (feat. Bebel Gilberto).mp3
08 - Celebrity Death Match (feat. Kid Koala).mp3
09 - How U Feelin (feat. Doseone).mp3
10 - Sucker (feat. Norah Jones).mp3
11 - We're Not Alone (remix) (feat. Dub Trio).mp3
Source Code
#!/usr/bin/env python3
import sys
import os
import math as m
import glob
import re
import mutagen
try:
dir = sys.argv[1]
except:
print("ERROR: Must provide a directory path.")
exit(1)
if not os.path.exists(dir):
print("ERROR: The directory must exist.")
exit(2)
# OPTIONS
# Format string for the new file name.
new_name = "{trackn} - {old_name}"
os.chdir(dir)
# Make sure mutagen uses the easy version, as
# it uses the normal one by default
extension = os.path.splitext(next(glob.iglob('*')))[1]
files = glob.glob('*'+extension)
if extension == ".mp3":
import mutagen.easyid3
mut_init = mutagen.easyid3.EasyID3
elif extension == ".m4a":
import mutagen.easymp4
mut_init = mutagen.easymp4.EasyMP4
else:
mut_init = mutagen.File
for song in files:
metadata = mut_init(song)
try:
trackn = re.search(r'\d+', metadata['tracknumber'][0]).group()
except KeyError:
continue
os.rename(song, new_name.format(trackn =
str(trackn).zfill(m.floor(m.log10(len(files)))+1), old_name = song))
Installation
Python 3 is required. You will also need the mutagen python package which can be installed using pip: sudo pip install mutagen
, or you can probably obtain it through your package manager.
Save the file as tracks.py
in either your $PATH
or your $VIFM/scripts
directory. Make sure that the file is executable.
Then you can run it in Vifm.