python3脚本批量重命名歌曲文件
场景:歌曲文件名有些混乱
于是想用个脚本批量重命名这些歌曲文件,可以选择【歌曲名 - 歌手】或【歌手 - 歌曲名】规范这些文件名
脚本如下:
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)
效果如下: