1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import mutagen
import os
import glob
#List all mp3 files in directory
def list_all_mp3():
return glob.iglob('*.mp3', recursive=False)
#Read the tag of the mp3 file
def get_mp3tag(file_name):
audio = mutagen.File(file_name)
album = (audio['TALB'].text)[0]
artist = (audio['TPE1'].text)[0]
return artist, album
#Verify if folder exist else create the folder
def create_folder(artist, album):
try:
os.makedirs(os.path.join(artist, album), exist_ok=False)
except OSError:
print("The directory has been already created")
#Move the music to the folder
def move_mp3file(file_name, artist, album):
create_folder(artist, album)
try:
os.rename(file_name, os.path.join(artist, album, file_name))
except OSError:
print("This music is already in the directory")
#Remove reserved characters
def remove_special_character(file_name):
return file_name.rstrip().translate({ord(c): None for c in '/\?%*:|"<>.'})
def main():
mp3_list = list_all_mp3()
for mp3 in mp3_list:
artist,album = get_mp3tag(mp3)
artist = remove_special_character(artist)
album = remove_special_character(album)
move_mp3file(mp3, artist, album)
if __name__ == "__main__":
main() |
Partager