import os import shutil target_path = './TestFiles' extensions = {item.split('.')[-1] for item in os.listdir(target_path) if os.path.isfile(os.path.join(target_path, item))} # print(extensions) for ext in extensions: # Create a folder for extension types if not os.path.exists(os.path.join(target_path, ext)): os.mkdir(os.path.join(target_path, ext)) # Move the files into the folder for item in os.listdir(target_path): if os.path.isfile(os.path.join(target_path, item)): file_extension = item.split('.')[-1] shutil.move(os.path.join(target_path, item), os.path.join(target_path, file_extension, item))