The problem is that the default os.walk is an excess. If you try to rename directories while going down, the results are unpredictable.
Try installing os.walk up:
for root, subFolders, files in os.walk(rootdir,topdown=False):
Edit
Another problem you are facing is listFiles() returns, well, files are not directories.
This (unchecked) sub-subdirectory directories from the bottom up:
def listDirs(dir): for root, subFolders, files in os.walk(dir, topdown=False): for folder in subFolders: yield os.path.join(root,folder) return
source share