Last active
May 5, 2024 07:26
-
-
Save cdecl/bf4cf8a79bd5027435c6bb5cb2a20b1f to your computer and use it in GitHub Desktop.
This file contains 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
import os | |
import shutil | |
import eyed3 | |
# Specify the root directory | |
root_dir = 'src_path' | |
output_dir = 'target_path' | |
# Recursively walk through all directories | |
for dir_path, dir_names, file_names in os.walk(root_dir): | |
for filename in file_names: | |
if filename.endswith('.mp3'): | |
# Construct the full file path | |
file_path = os.path.join(dir_path, filename) | |
try: | |
# Load the MP3 file metadata | |
audio_file = eyed3.load(file_path) | |
# Get the artist, album, track number, and title tags | |
artist = audio_file.tag.artist or 'Unknown' | |
album = audio_file.tag.album or 'Unknown' | |
track_number = str(audio_file.tag.track_num[0] or 0).zfill(2) | |
title = audio_file.tag.title or 'Unknown' | |
except Exception as e: | |
print(f"Error reading metadata for '{filename}': {e}") | |
artist = 'Unknown' | |
album = 'Unknown' | |
track_number = '00' | |
title = 'Unknown' | |
# Replace invalid characters in the artist, album name, and title | |
artist = ''.join(c for c in artist if c.isalnum() or c in [' ', '.', '-', '_']) | |
album = ''.join(c for c in album if c.isalnum() or c in [' ', '.', '-', '_']) | |
title = ''.join(c for c in title if c.isalnum() or c in [' ', '.', '-', '_']) | |
# Create the artist directory if it doesn't exist | |
artist_dir = os.path.join(output_dir, artist) | |
if not os.path.exists(artist_dir): | |
os.makedirs(artist_dir) | |
# Create the album directory if it doesn't exist | |
album_dir = os.path.join(artist_dir, album) | |
if not os.path.exists(album_dir): | |
os.makedirs(album_dir) | |
# Construct the new filename with track number and title | |
new_filename = f"{track_number} - {title}.mp3" | |
new_file_path = os.path.join(album_dir, new_filename) | |
# Move the file to the album directory | |
# shutil.move(file_path, new_file_path) | |
shutil.copy(file_path, new_file_path) | |
print(f"Moved '{filename}'") | |
print(f" '{new_filename}'") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment