🐍️ Synchronize folder names between two directories

This code segment helps me to synchronize folder names between two directories (typically, a local one on disk and an remote one on NAS).

import os

directory_A = r'V:\\CameraRoll\\Picture\\2022\\03\\'
directory_B = r'D:\\Mem\\Photo\\03\\'

# Check if the directories exist
if not os.path.exists(directory_A) or not os.path.exists(directory_B):
    print("Either directory A or directory B does not exist. Please make sure both exist.")
    exit(1)

# Iterate/traverse folders in directory_A
for folder_name_A in os.listdir(directory_A):
    
    # Read the first 10 characters of the folder's name in directory_A
    prefix_A = folder_name_A[:10]
    
    # Initialize variable to hold matching folder's name in directory_B
    folder_name_B = None
    
    # Find the folder's name in directory_B with the same first 10 characters
    for candidate_folder_name_B in os.listdir(directory_B):
        if candidate_folder_name_B.startswith(prefix_A):
            folder_name_B = candidate_folder_name_B
            break
    
    # If a folder in directory_B with matching first 10 characters is found
    if folder_name_B:
        # Check if folder_name_A is the same as folder_name_B
        if folder_name_A == folder_name_B:
            print(f"{folder_name_A} is already named correctly. Skipping.")
            continue
        
        # Prompt for confirmation before renaming
        confirmation = input(f"Do you want to rename {folder_name_A} to {folder_name_B}? (y/n): ")
        
        if confirmation.lower() == 'y':
            # Rename folder in directory_A to folder_name_B
            original_path_A = os.path.join(directory_A, folder_name_A)
            new_path_A = os.path.join(directory_A, folder_name_B)
            
            os.rename(original_path_A, new_path_A)
            print(f"Renamed {folder_name_A} to {folder_name_B}.")
        else:
            print(f"Skipped renaming {folder_name_A}.")

    else:
        print(f"No matching folder found in directory B for {folder_name_A}.")

Last updated

Was this helpful?