Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recursively loop through a file structure and rename directories in python

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"
like image 482
Robert Buckley Avatar asked Nov 30 '11 19:11

Robert Buckley


1 Answers

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
like image 200
dawg Avatar answered Sep 21 '22 12:09

dawg