Created
September 7, 2021 11:44
-
-
Save taikedz/ed86d91ebcac9a22dc79c05abdeaefe2 to your computer and use it in GitHub Desktop.
Tool to rename tracks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Rename files | |
rename-tracks.py TRACKFILE [apply] | |
TRACKFILE is a basic text file, each line containing a track name. | |
This script naively looks for the track name in each file name. | |
If found, the old file name and new file name are printed. | |
If a title matches multiple files, an error is raised. | |
If 'apply' was supplied as the script's second argument, | |
and no file or title clashes were found, | |
the proposed rename is effectively applied. | |
If a new filename matches an existing file, the rename is not performed | |
for that file pair. | |
""" | |
import sys | |
import os | |
def enumerate_tracks(track_list): | |
tracks_numbered = {} | |
for i,name in enumerate(track_list): | |
tracks_numbered[name] = str(i+1).zfill(3) | |
return tracks_numbered | |
def file_exists(new_f): | |
if os.path.exists(new_f): | |
print(f" --x {new_f} already exists ! Not renaming/overwriting.") | |
return True | |
return False | |
def main(): | |
with open(sys.argv[1]) as fh: | |
tracks = [line.strip() for line in fh.readlines() if line.strip()] | |
file_list = os.listdir() | |
renames = {} | |
for track_name,track_number in enumerate_tracks(tracks).items(): | |
found_files = [filename for filename in file_list if track_name in filename] | |
if len(found_files) == 1: | |
new_filename = f'{track_number}-{track_name}.mp3' | |
f = found_files[0] | |
print(f"{f} --> {new_filename}") | |
renames[f] = new_filename | |
file_exists(new_filename) | |
else: | |
raise ValueError(f"Title conflict - ''{track_name}'' must match exactly 1 file, got: {found_files}") | |
if sys.argv[2:3] == ["apply"]: | |
print("Applying renames.") | |
for old_f, new_f in renames.items(): | |
if not file_exists(new_f): | |
os.rename(old_f, new_f) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment