How can I rename folders to 'surname, firstname' in Python?

Okay, from my experience, renaming folders in Python is quite straightforward using os.rename and split. You can use this method if your folders follow a standard format (e.g., first name followed by surname). Here’s how you can do it:

import os

folder_path = "C:/Test"
for folder_name in os.listdir(folder_path):
    folder_full_path = os.path.join(folder_path, folder_name)
    
    if ',' in folder_name:
        continue  # Skip if the folder name already contains a comma
    
    # Split the name by spaces
    name_parts = folder_name.split()
    surname = name_parts[-1]
    first_names = ' '.join(name_parts[:-1])
    
    # Construct the new name
    new_name = f"{surname}, {first_names}"
    
    # Rename the folder
    new_folder_full_path = os.path.join(folder_path, new_name)
    os.rename(folder_full_path, new_folder_full_path)
    print(f"Renamed {folder_name} to {new_name}")

This should work fine for single first names, and it’s simple to use. Of course, if you’re using a version of Python where you’re dealing with Python 2to3 transitions, you’d want to ensure everything’s compatible.