I find myself often wanting to move a file in a directory tree to same place under a different parent directory. Usually this is because I have a directory tree that I want to separate into different bins depending on criteria. The upshot of which is that I’ve written python code similar to the below sample a bunch of times, so it seemed time to stick it somewhere where I could easily find it. At work it is safely stuffed in svn, but I don’t really have a svn repository for home. Hmmm….
Anyway this just moves a file. It creates the new directory structure before moving the file and prunes off any empty directories once the file has been moved. It thows an OSError if there are permissions issues at any point.
So here’s a simple movefile in python.
import os import os.path
#Just some junk for testing
if 1:
newroot = '/misc/tkusterer/test/old/'
oldroot = '/misc/tkusterer/test/new/'
else:
oldroot = '/misc/tkusterer/test/old/'
newroot = '/misc/tkusterer/test/new/'
src = os.path.join(oldroot, '2/3/hello.txt')
def movefile(src, dst):
try:
os.makedirs(os.path.split(dst)[0])
except OSError, e:
# Already Exists
if e.errno != 17:
raise
os.rename(src,dst)
try:
os.removedirs(os.path.split(src)[0])
except OSError, e:
# Leaf directory not empty
if e.errno != 39:
raise
if __name__=="__main__":
dst = src.replace(oldroot, newroot)
movefile(src, dst)
No user comments about " Move a File w/ Directory Maintenence "
Follow-up comment rss or Leave a TrackbackLeave A Reply