[Tutor] walking down directories

Steve Slevinski slevin at signpuddle.net
Fri Mar 17 20:10:46 CET 2006


Recursion. 

if os.path.isdir(d): describeDirectory(d)

Since your printing from the function itself, you may want to add a 
level or depth arguement with a default value of 0.

def describeDirectory(directory, level=0):

Then call the function recursively with describeDirectory(d,level+1)

Use the level variable in the print statements for proper indentation.

Or something like that,
-Steve

Christopher Spears wrote:
> 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.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   


More information about the Tutor mailing list