[Tutor] Move all files to top-level directory

Dave Angel davea at ieee.org
Tue Apr 13 14:16:05 CEST 2010


Dotan Cohen wrote:
> Here is the revised version:
>
> #!/usr/bin/python
> # -*- coding: utf-8 -*-
> import os
> currentDir = os.getcwd()
> i = 1
> filesList = os.walk(currentDir)
> for rootDirs, folders, files in filesList:
>   
Actual the first item in the tuple (returned by os.walk) is singular (a 
string), so I might call it rootDir.  Only the other two needed to be 
changed to plural to indicate that they were lists.
>     for f in files:
>         if (rootDirs!=currentDir):
>             toMove      = os.path.join(rootDirs, f)
>             print "--- "+str(i)
>             print toMove
>             newFilename = os.path.join(currentDir,f)
>             renameNumber = 1
>             while(os.path.exists(newFilename)):
>                 print "- "+newFilename
>                 newFilename = os.path.join(currentDir,f)+"_"+str(renameNumber)
>                 renameNumber = renameNumber+1
>             print newFilename
>             i=i+1
>             os.rename(toMove, newFilename)
>
> Now, features to add:
> 1) Remove empty directories. I think that os.removedirs will work here.
> 2) Prevent race conditions by performing the filename check during
> write. For that I need to find a function that fails to write when the
> file exists.
> 3) Confirmation button to prevent accidental runs in $HOME for
> instance. Maybe add some other sanity checks. If anybody is still
> reading, I would love to know what sanity checks would be wise to
> perform.
>
> Again, thanks to all who have helped.
>
>
>   
Note that it's not just race conditions that can cause collisions.  You 
might have the same name in two distinct subdirectories, so they'll end 
up in the same place.  Which one wins depends on the OS you're running, 
I believe.

DaveA


More information about the Tutor mailing list