# Author: Jose Stovall ## This Script goes through all songs in a given directory and reorganizes them like ## iTunes' Library Management does, running just on the tags of the file alone. ## This means the input will be <>, and the output will transform all files ## in <> to <> from os import listdir, makedirs from pathlib import Path from tinytag import TinyTag from argparse import ArgumentParser from pathvalidate import sanitize_filepath from shutil import move as mv def process_file(file: Path, output_root: Path) -> None: """Processes a given file, grabbing metadata using TinyTag and then creating the subdirectories as needed Args: file (Path): The music file being processed output_root (Path): Where the first level and beyond of subdirs should start from Raises: Exception: If any required fields aren't propagated """ tag: TinyTag = TinyTag.get(file) if not tag.albumartist: raise Exception("Tag is missing an Artist!") if not tag.album: raise Exception("Tag is missing an Album!") if not tag.title: raise Exception("Tag is missing a Title!") output_dir = sanitize_filepath(output_root.joinpath(tag.albumartist).joinpath(tag.album).resolve()) makedirs(output_dir, exist_ok=True) new_name = sanitize_filepath(output_dir.joinpath(tag.title.replace("/", "-")).with_suffix(file.suffix)) mv(file, new_name) def main(args) -> None: input_dir = Path(args.input_dir).resolve() output_dir = Path(args.output or args.input_dir).resolve() for file in listdir(input_dir): try: file_path = input_dir.joinpath(input_dir).joinpath(file).resolve() process_file(file_path, output_dir) except Exception as e: print(f"Failed to process {file}: {e}") if __name__ == "__main__": parser = ArgumentParser( prog="Music Folder Organizer", description="See head of organize.py", ) parser.add_argument("input_dir") parser.add_argument("-o", "--output", default=None) args = parser.parse_args() main(args)