6.4 pathlib פתרון

from pathlib import Path
import shutil

def organize_files(directory_path):
    directory = Path(directory_path)

    # Create a list of all files in the directory
    files = [file for file in directory.iterdir() if file.is_file()]

    # Create subdirectories for each unique file extension
    for file in files:
        extension = file.suffix.lower()  # Get the file extension (e.g., '.txt', '.jpg')
        if extension:
            # Create the subdirectory if it doesn't exist
            if not (directory / extension[1:]).exists():
                (directory / extension[1:]).mkdir()
            # Move the file to the corresponding subdirectory
            shutil.move(file, directory / extension[1:])

def main():
    directory_path = input("Enter the directory path to organize files: ")
    organize_files(directory_path)
    print("Files organized successfully!")

if __name__ == "__main__":
    main()