import os import random # Directory paths dir1 = 'cloth_s' dir2 = 'cloth-mask_s' # Ensure both directories have the same set of filenames assert sorted(os.listdir(dir1)) == sorted(os.listdir(dir2)), "Directories do not have the same set of files" # Get the list of filenames without extension from one directory filenames = [os.path.splitext(f)[0] for f in os.listdir(dir1)] # Shuffle the list of filenames random.shuffle(filenames) # Create mappings for new filenames in both directories new_filenames = {os.path.splitext(f)[0]: new_name for f, new_name in zip(sorted(os.listdir(dir1)), filenames)} # Rename files in both directories for dir in [dir1, dir2]: for old_file in os.listdir(dir): old_base, ext = os.path.splitext(old_file) # Only rename if the file is in the mapping if old_base in new_filenames: new_file = new_filenames[old_base] + ext os.rename(os.path.join(dir, old_file), os.path.join(dir, new_file))