|
| 1 | +import os |
| 2 | +import shutil |
| 3 | + |
| 4 | + |
| 5 | +# BONUS: Create a tkinter app that allows the user to select the file via a button |
| 6 | + |
| 7 | +def create_folder(path: str, extension: str) -> str: |
| 8 | + """Creates a folder that is named after the extension of the file passed in""" |
| 9 | + |
| 10 | + # Create the folder name excluding the dot "." |
| 11 | + folder_name: str = extension[1:] |
| 12 | + |
| 13 | + # Create a valid path with the new folder name |
| 14 | + folder_path: str = os.path.join(path, folder_name) |
| 15 | + |
| 16 | + # If the folder path doesn't exist yet, create it |
| 17 | + if not os.path.exists(folder_path): |
| 18 | + os.makedirs(folder_path) |
| 19 | + |
| 20 | + # Return the new path |
| 21 | + return folder_path |
| 22 | + |
| 23 | + |
| 24 | +def sort_files(source_path: str): |
| 25 | + """Sorts files based on a given path""" |
| 26 | + |
| 27 | + # Recursively walk through all the directories and files in the source path |
| 28 | + for root_dir, sub_dir, filenames in os.walk(source_path): |
| 29 | + |
| 30 | + # Get the full path for each file |
| 31 | + for filename in filenames: |
| 32 | + file_path: str = os.path.join(root_dir, filename) |
| 33 | + |
| 34 | + # Splits the path into a root and the extension |
| 35 | + extension: str = os.path.splitext(filename)[1] |
| 36 | + |
| 37 | + # Check that there is an extension and create a folder if there is |
| 38 | + if extension: |
| 39 | + target_folder: str = create_folder(source_path, extension) |
| 40 | + |
| 41 | + # Create a path that leads to the target folder |
| 42 | + target_path: str = os.path.join(target_folder, filename) |
| 43 | + |
| 44 | + # Move the file from its current location to the target folder |
| 45 | + shutil.move(file_path, target_path) |
| 46 | + |
| 47 | + |
| 48 | +def remove_empty_folders(path): |
| 49 | + """Removes all empty folders""" |
| 50 | + |
| 51 | + # We walk through all our folders again, but this time in a bottom-up approach |
| 52 | + for root_dir, sub_dir, filenames in os.walk(path, topdown=False): |
| 53 | + |
| 54 | + # Create a valid folder path for each dir |
| 55 | + for current_dir in sub_dir: |
| 56 | + folder_path: str = os.path.join(root_dir, current_dir) |
| 57 | + |
| 58 | + # Check if a folder is empty, and removes it if it is |
| 59 | + if not os.listdir(folder_path): |
| 60 | + os.rmdir(folder_path) |
| 61 | + |
| 62 | + |
| 63 | +def main(): |
| 64 | + # Get some user input |
| 65 | + user_input: str = input('Please provide a file path to sort: ') |
| 66 | + |
| 67 | + # Check if the path the user provided exists |
| 68 | + if os.path.exists(path=user_input): |
| 69 | + sort_files(user_input) |
| 70 | + remove_empty_folders(user_input) |
| 71 | + print('Files sorted successfully!') |
| 72 | + else: |
| 73 | + print('Invalid path, please provide a valid file path.') |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == '__main__': |
| 77 | + main() |
0 commit comments