Skip to content

Instantly share code, notes, and snippets.

@benchi99
Created April 7, 2023 11:46
Show Gist options
  • Select an option

  • Save benchi99/d61999a3dd5c2243089836c9eede709b to your computer and use it in GitHub Desktop.

Select an option

Save benchi99/d61999a3dd5c2243089836c9eede709b to your computer and use it in GitHub Desktop.
bandcamp, why the hell can't you name your downloaded album track files so the NUMBER is the first thing in the file, files do NOT sort properly if the files start with the artist name man
# Upon running this script on a directory you pass as a first argument to it,
# it'll rename all files it can find with the following structure:
# "{artist name} - {album name} - {song number and name}.{file extension}"
# to follow this structure instead:
# "{song number and name} - {artist name}.{file extension}"
import os, sys, re
regex_artist_name = r'^[^0-9]{2}.*?- '
regex_group_song_name_and_extension = r'^([^0-9]{2}.*? -) ([0-9]{2}.*)(\.mp3|\.flac|\.m4a|\.ogg|\.wav|\.aiff)'
regex_allowed_file_extensions = r'\.(mp3|flac|m4a|ogg|wav|aiff)$'
def extract_relevant_data(file_name):
name_and_extension_match = re.match(regex_group_song_name_and_extension, file_name)
artist_match = re.match(regex_artist_name, file_name)
artist = artist_match.group(0).removesuffix(' - ')
song_name = name_and_extension_match.group(2)
file_extension = name_and_extension_match.group(3)
return artist, song_name, file_extension
def rename_file(directory_path, old_filename, new_filename):
try:
os.rename(f'{directory_path}\\{old_filename}', f'{directory_path}\\{new_filename}')
except FileExistsError:
print(f'File {new_filename} already exists in this directory!')
except FileNotFoundError:
print(f'File {old_filename} doesn\'t exist!')
try:
path = sys.argv[1]
except IndexError:
print('Please pass in the directory containing the album tracks to rename.')
exit(1)
processed_count = 0
for root, dir_names, file_names in os.walk(path):
print(f'Found {len(file_names)} files in specified directory')
for file_name in file_names:
# match bad file names
if re.search(regex_artist_name, file_name) and re.search(regex_allowed_file_extensions, file_name):
print(f'Bad filename found: {file_name}')
artist, song_name, file_extension = extract_relevant_data(file_name)
# build final file name
resulting_file_name = f'{song_name} - {artist}{file_extension}'
print(f'Resulting filename: {resulting_file_name}')
# rename it
rename_file(path, file_name, resulting_file_name)
processed_count += 1
print(f'Processed {processed_count} files.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment