tags:

views:

68

answers:

4
#Moving up/down dir structure
print os.listdir('.')
print os.listdir('..')
print os.listdir('../..')

Any othe ways??? I got saving dirs before going deeper, then reassigning later.

+1  A: 

Of course there are - thre are both os.walk - which returns tuples with the subdirectories, and the files tehrein as os.path.walk, which takes a callback function to be called for each file in a directory structure.

You can check the online help for both functions.

jsbueno
btw. for getting you this answer I inferred you want to do this only due to your "saving dirs before going deeper" comment. If you want just to change dirs, os.chdir is obviously the right answer.
jsbueno
Well I guess I was going to try to have some temporary place holders. For example, I'll be changing between the parent and child a lot in certain methods. I think I'll just try saving the state. Thanks
shawn
A: 

You can use os.chdir()

http://docs.python.org/library/os.html#os-file-dir

Am I missing something in the question?

dkamins
+3  A: 

This should do the trick:

for root, dirs, files in os.walk(os.getcwd()):
    for name in dirs:
        try:
            os.rmdir(os.path.join(root, name))
        except WindowsError:
            print 'Skipping', os.path.join(root, name)

This will walk the file system beginning in the directory the script is run from. It deletes the empty directories at each level.

Steven
and what if you wanted to move all the files up to the root directory?
shawn
I'm just curious. I actually got it working, but it was like 80 lines of code... lol
shawn
A: 

"and what if you wanted to move all the files up to the root directory?"

You could do something like:

for root, dirs, files in os.walk(os.getcwd()):
    for f in files:
        try:
            shutil.move(os.path.join(root, f), os.getcwd())
        except:
            print f, 'already exists in', os.getcwd()
Steven