import os import shutil EXCLUDE_FILE = 'DownloadSorter.py' def create_dir(path, extensions): for ext in extensions: if not os.path.exists(os.path.join(path, ext)): os.mkdir(os.path.join(path, ext)) def move_files(target_path): for file in os.listdir(target_path): if os.path.isfile(os.path.join(target_path, file)) and file != EXCLUDE_FILE: file_extension = file.split('.')[-1] shutil.move(os.path.join(target_path, file), os.path.join(target_path, file_extension, file)) def main(): while True: # Get current directory and set it as the target path cwd = os.getcwd() target_path = os.path.join(cwd) # Set up the number of files originally for automation number_of_files = len(os.listdir(cwd)) time.sleep(20) old_number = number_of_files number_of_files = len(os.listdir(cwd)) # If new files detected, organize them if number_of_files != old_number: # Get all file extensions present in the directory extensions = {item.split('.')[-1] for item in os.listdir(target_path) if os.path.isfile(os.path.join(target_path, item))} # print(extensions) # Create a folder for extension types create_dir(target_path, extensions) # Move the files into the folder move_files(target_path) main()