diff options
author | Jackson Taylor <jackson@jacksontaylor.xyz> | 2023-05-10 12:57:44 -0400 |
---|---|---|
committer | Jackson Taylor <jackson@jacksontaylor.xyz> | 2023-05-10 12:57:44 -0400 |
commit | afe4e5972a3b50756cb5575946389a344d8caf6e (patch) | |
tree | 845f444cfe21554505ddceb2ffa591176fc158c1 /file_operations.py | |
parent | 56da4e191267147318b2ab2010d92b22fac747da (diff) |
Move all file operations to separate modulejackson/structure-refactoring
Diffstat (limited to 'file_operations.py')
-rw-r--r-- | file_operations.py | 61 |
1 files changed, 61 insertions, 0 deletions
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!") |