python3指令碼批次重新命名歌曲檔案

请叫我小马驹發表於2024-08-22

場景:歌曲檔名有些混亂

於是想用個指令碼批次重新命名這些歌曲檔案,可以選擇【歌曲名 - 歌手】或【歌手 - 歌曲名】規範這些檔名

指令碼如下:

import os
import re 
from mutagen.id3 import ID3, TIT2, TPE1
from mutagen.mp4 import MP4

# 替換後歌手分隔符
REPLACEMENT_STRING = '_'
# 需要被替換掉分隔符
CHARACTERS_TO_REPLACE = ['&', ',', '',' /', '/']

def replace_characters_in_string(s):
    # 替換字串中的指定字元
    for char in CHARACTERS_TO_REPLACE:
        s = s.replace(char, REPLACEMENT_STRING)
    return s

def get_title_and_artist(filepath):
    """獲取歌曲標題和藝術家"""
    if filepath.lower().endswith('.mp3'):
        audio = ID3(filepath)
        title = audio.get('TIT2', None)
        artist = audio.get('TPE1', None)
        if title and artist:
            return title.text[0], artist.text[0]
    elif filepath.lower().endswith('.m4a'):
        audio = MP4(filepath)
        title = audio.get('\xa9nam', None)
        artist = audio.get('\xa9ART', None)
        if title and artist:
            return title[0], artist[0]
    return None, None

def rename_file(filepath, format_choice):
    """重新命名檔案"""
    title, artist = get_title_and_artist(filepath)
    if title and artist:
        # 替換掉歌手中非法字元
        artist = replace_characters_in_string(artist)
        # 根據格式選擇構建新的檔名
        if format_choice == '1':
            new_name = f"{title} - {artist}"
        elif format_choice == '2':
            new_name = f"{artist} - {title}"
        else:
            print("Invalid format choice. Please choose 1 or 2.")
            return

        # 生成新的檔案路徑
        dir_name = os.path.dirname(filepath)
        new_filepath = os.path.join(dir_name, f"{new_name}{os.path.splitext(filepath)[1]}")
        # 重新命名檔案
        os.rename(filepath, new_filepath)
        print(f'Renamed file: {filepath} -> {new_filepath}')
    else:
        print(f'Failed to get title or artist for file: {filepath}')

def process_directory(directory, format_choice):
    """遍歷目錄並重新命名檔案"""
    for root, dirs, files in os.walk(directory):
        for file in files:
            filepath = os.path.join(root, file)
            if file.lower().endswith(('.mp3', '.m4a')):
                rename_file(filepath, format_choice)

if __name__ == "__main__":
    directory = input("Enter the directory path to process: ")
    format_choice = input("Choose the renaming format:\n1. Song Title - Artist\n2. Artist - Song Title\nEnter 1 or 2: ")
    process_directory(directory, format_choice)

效果如下:

相關文章