def substitute_dir_in_path(path, olddir, newdir): pp = PurePath(path) parts = [p if p != olddir else newdir for p in pp.parts] return os.path.join(*parts)