[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:
#!/usr/bin/python
# -*- 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
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.
--
Dotan Cohen
http://bido.com
http://what-is-what.com
More information about the Tutor
mailing list