Mass-Renaming folders win32

Tim Chase python.list at tim.thechases.com
Sat Oct 28 09:43:22 EDT 2006


> I've a folder structure like this :
> 
> "Folder A"
> |--> "1"
> |--> "2"
> ---> "3"
> 
> "Folder B"
> |--> "4"
> ---> "5"
> 
> And I want to obtain a structure like this :
> 
> "Folder A - 1"
> "Folder A - 2"
> "Folder A - 3"
> "Folder B - 4"
> "Folder B - 5"
> 
> Can someone help me ? I am python beginner

I'd try something like:

import os
from shutil import move

for path, dirs, files in os.walk('.'):
   if path <> os.curdir and files:
     # the "2:" strips of the ".[os.sep]" at the beginning
     newdir = path[2:].replace(os.sep, ' - ')
     try:
       os.mkdir(newdir)
       for f in files:
         try:
           move(
             os.sep.join([path, f]),  #the old location
             os.sep.join([newdir, f]) #the new location
             )
         except:
           print 'Could not move %s to %s' % (f, newdir)
     except:
       print 'Could not create %s' % newdir



It doesn't clean up the original directories along the way, but 
that may be better, depending on the nesting depth of your 
directories...you'd want to make sure that you deal with all the 
files within a directory before deleting it.

Feel free to tweak as needed.

-tkc









More information about the Python-list mailing list