From afe4e5972a3b50756cb5575946389a344d8caf6e Mon Sep 17 00:00:00 2001 From: Jackson Taylor Date: Wed, 10 May 2023 12:57:44 -0400 Subject: Move all file operations to separate module --- file_operations.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 file_operations.py (limited to 'file_operations.py') diff --git a/file_operations.py b/file_operations.py new file mode 100644 index 0000000..9cb74fe --- /dev/null +++ b/file_operations.py @@ -0,0 +1,61 @@ +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!") -- cgit v1.2.3