By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,156 Members | 1,026 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,156 IT Pros & Developers. It's quick & easy.

File/Directory hacks - is there a better way to do this?

P: n/a
I had a software package screw up a directory tree by placing all the
files in a directory of the same name. So I wound up with:

Root
file1.txt (dir)
file1.txt (file)

file2.txt (dir)
file2.txt (file)

Annoying. So I wrote the following script, which fixed the problem by
renaming and copying the file up to the root directory, removing the
intermediate directory, and finally restoring the orginal file name.

Is there a better (faster, or fewer lines of code, or more
'python-esque') way to do? In particular, I know the latest versions
of python includes iterators, generators, and decorators...but I
haven't had a chance to really read about them, or understand how to
use them properly. So I'd love to hear if the new tools could've
solved this simpler/faster.

Thanks!

------------------------------------------------------

#!/user/bin/env python

import os, os.path, shutil

top = 'c:\$user'

class fixdirectories:
def __init__(self, top):
self.top = top

def walk(self):
for root, dirs, files in os.walk(self.top, topdown=False):
rootdir, roottail = os.path.split(root)
for name in files:
if name.lower() == roottail:

oldname = os.path.join(root, name)
tmpname = os.path.join(rootdir, "PRE-" + name)
newname = os.path.join(rootdir, name)

shutil.move(oldname, tmpname)
try:
os.rmdir(root)
print "removing: " + rootdir
shutil.move(tmpname, newname)
except:
print "Could not remove: " + root

if __name__ == "__main__":
f = fixdirectories(top)
f.walk()

Jul 18 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.