Help | Site Map
Connecting Tech Pros Worldwide
 
 
LinkBack Thread Tools
  #1  
Old July 18th, 2005, 10:56 PM
Fitzgerald Steele
Guest
 
Posts: n/a
Default File/Directory hacks - is there a better way to do this?

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()

 

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles