sorting for recursive folder rename

MRAB google at mrabarnett.plus.com
Tue Dec 16 14:00:20 EST 2008


ianaré wrote:
> Hello all,
> 
> I trying to recursively rename folders and files, and am looking for
> some ideas on the best way of doing this. The problem is that the
> given list of items can be in order, and one to all items may be
> renamed. Here is some preliminary code I have, but which does not work
> very well.
> 
> self.toRename has the following structure :
> [
> [original_name, new_name, os.path.isdir]
> ..
> ]
> 
> # define these here for faster processing
> def split(item):
>     return os.path.split(item)
> def addSep(path):
>     return os.sep + path + os.sep
> def recursiveFolderSort(x,y):
>     return cmp(y[0], x[0])
> 
> sortedRename = sorted(self.toRename)
> 
> # make a list of all folders that will be processed
> foldersToAdjust = []
> for item in sortedRename:
>     if item[2] is False:
      if not item[2]:
>         oF = split(item[0])[1] # original folder name
>         nF = split(item[1])[1] # new folder name
>         if oF is not nF:
          if oF != nF:
>             foldersToAdjust.append((oF, nF))
> 
> # replace all occurences of folders in path
> for i in range(len(self.toRename)):
>     for f in foldersToAdjust:
>         oF = addSep(f[0]) # original folder name
>         nF = addSep(f[1]) # new folder name
>         self.toRename[i][0] = self.toRename[i][0].replace(oF,nF)
>         self.toRename[i][1] = self.toRename[i][1].replace(oF,nF)
> 
>     if progressDialog.update(i) is False:
      if not progressDialog.update(i):
>         error = 'cancelled'
>         break
> 
> # make sure renaming will be in correct order !
> self.toRename.sort(recursiveFolderSort)
> 
> 
> 
> First problem is adjusting the paths can take a very long time.
> Second problem is sorting is not always right and files get lost !!
> Any input welcome.
> 
You should use "is" and "is not" _only_ when checking for _identity, ie 
are these 2 both references to the _same_ object. Most of the time that 
would be "x is None" or "x is not None".



More information about the Python-list mailing list