Reputation: 11926
I would like to resursively rename directories by changing the last character to lowercase (if it is a letter)
I have done this with the help of my previous posts (sorry for the double posting and not acknowledging the answers)
This code works for Files, but how can I adapt it for directories as well?
import fnmatch
import os
def listFiles(dir):
rootdir = dir
for root, subFolders, files in os.walk(rootdir):
for file in files:
yield os.path.join(root,file)
return
for f in listFiles(r"N:\Sonstiges\geoserver\IM_Topo\GIS\MAPTILEIMAGES_0\tiles_2"):
if f[-5].isalpha():
os.rename(f,f[:-5]+f[-5].lower() + ".JPG")
print "Renamed " + "---to---" + f[:-5]+f[-5].lower() + ".JPG"
Upvotes: 6
Views: 8026
Reputation: 103774
The problem is that the default of os.walk is topdown. If you try to rename directories while traversing topdown, the results are unpredictable.
Try setting os.walk
to go bottom up:
for root, subFolders, files in os.walk(rootdir,topdown=False):
Edit
Another problem you have is listFiles()
is returning, well, files not directories.
This (untested) sub returns directories from 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
Upvotes: 7