#!/usr/bin/env python3 import os to_replace = ":" replace_by = " " DRY_RUN = False for (dirpath, dirnames, filenames) in os.walk("/root/of/path", topdown=False): if DRY_RUN: print("DRY RUN ", end="") print(f"Current folder: {dirpath}") for filename in filenames: new_name = filename if to_replace in filename: new_name = filename.replace(to_replace, replace_by) # remove leading and trailing spaces and limit to one consecutive space split_string = new_name.split(' ') new_name = ' '.join(item for item in split_string if item) if filename != new_name: print(f" Renamed file \"{filename}\" to \"{new_name}\"") if not DRY_RUN: os.rename(os.path.join(dirpath, filename), os.path.join(dirpath, new_name)) for dirname in dirnames: new_name = dirname if to_replace in dirname: new_name = dirname.replace(to_replace, replace_by) # remove leading and trailing spaces and limit to one consecutive space split_string = new_name.split(' ') new_name = ' '.join(item for item in split_string if item) if dirname != new_name: print(f" Renamed dir \"{dirname}\" to \"{new_name}\"") if not DRY_RUN: os.rename(os.path.join(dirpath, dirname), os.path.join(dirpath, new_name))