[Tutor] Move all files to top-level directory

Dotan Cohen dotancohen at gmail.com
Tue Apr 13 11:31:54 CEST 2010

Here is the revised version:

# -*- coding: utf-8 -*-
import os
currentDir = os.getcwd()
i = 1
filesList = os.walk(currentDir)
for rootDirs, folders, files in filesList:
    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
                print "- "+newFilename
                newFilename = os.path.join(currentDir,f)+"_"+str(renameNumber)
                renameNumber = renameNumber+1
            print newFilename
            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

Again, thanks to all who have helped.

Dotan Cohen


More information about the Tutor mailing list