[Tutor] walking down directories

Christopher Spears cspears2002 at yahoo.com
Fri Mar 17 19:43:55 CET 2006


I am trying to write a function that takes a
directory's name, finds any subdirectories, and then
prints out the size of the files in all found
directories.

import os, os.path

def describeDirectory(directory):
    dirList = [directory]
    for d in os.listdir(directory):
        if os.path.isdir(d):
            dirList.append(d)
    for d in dirList:
        print d, ':'
        for f in os.listdir(d):
            name = os.path.join(d, f)
            print '\t', name, 'SIZE: ',
os.path.getsize(name)

describeDirectory('.')

Here is the output:

>>> 
. :
	.\changePeppers.py SIZE:  915
	.\describeDirectory.py SIZE:  549
	.\describeDirectory.pyc SIZE:  514
	.\describeDirectory01.py SIZE:  388
	.\error_log SIZE:  778
	.\makezeros.py SIZE:  147
	.\makezeros.pyc SIZE:  481
	.\modPrompt.py SIZE:  342
	.\modPrompt.pyc SIZE:  698
	.\output SIZE:  387
	.\pepper.txt SIZE:  601
	.\testFiles SIZE:  0
	.\textWrapper.py SIZE:  619
	.\textWrapper.pyc SIZE:  1092
	.\timings.py SIZE:  567
	.\timings.pyc SIZE:  733
testFiles :
	testFiles\renameFiles.py SIZE:  351
	testFiles\some_date SIZE:  29
	testFiles\stupid_text.txt SIZE:  12
	testFiles\testDir SIZE:  0

As you see, the problem is that there is another
directory under testFiles called testDir, but the
function doesn't check the directory for files.  The
function needs to find every directory (including
subdirectories within directories).  Any hints?  

I'm starting to wonder if I should abandon trying to
do this with one function.  For example, I could
create one function that finds every directory.  This
information would then be passed to another function
that returns the files' sizes.


More information about the Tutor mailing list