import errors import os from pathlib import Path import shutil def remove_special_characters_for_filename(filename): special_chars = [ ['-', ' '], ['(', ''], [')', ''], ['/', ' '], ['/', ' '], [' ', '_'], ["'", ''], ["&", 'and'], [chr(8217), ''], ['$', 's'], ['.', ''] ] new_name = filename for char_set in special_chars: new_name = new_name.replace(char_set[0], char_set[1]) return new_name.lower() def save_debug_data(filename, data, debug=True): if debug: with open(filename, 'w') as f: f.write(data) def move_song_to_permanent_location(music_directory, song_data, filename): try: # move song to music_directory/artist/album/artist_album_title.ext # excluding non filesafe characters artist_for_filename = remove_special_characters_for_filename( song_data['artists'][0]) album_for_filename = remove_special_characters_for_filename( song_data['album']) title_for_filename = remove_special_characters_for_filename( song_data['title']) song_output_dir = os.path.join(music_directory, artist_for_filename, album_for_filename) try: Path(song_output_dir).mkdir(parents=True, exist_ok=True) except OSError as ex: raise errors.UnableToCreateAlbumDirectoryError(ex) new_filename = '{}_{}_{}.mp3'.format(artist_for_filename, album_for_filename, title_for_filename) shutil.move(filename, os.path.join(song_output_dir, new_filename)) except Exception: print("could not move file to correct directory!")