[Tutor] Finding bottom level directories, and command-line arguments

Alan Gauld alan.gauld at freenet.co.uk
Thu Feb 9 10:25:20 CET 2006


I've been away so missed this thead earlier but one wee 
thing I just noticed:

>> -------
>> def isBottomDir(path):
>>     for item in os.listdir(path):
>>         if os.path.isdir(os.path.join(path,item)):
>>             return False
>>     return True
>> -------
>> for root, dirs, files in os.walk('~\Test'):
>>     if test_dir.isBottomDir(root) == True: print root
>> -------

Can be done more simply with:

for root,dirs,files in os.walk('~/Test'):
     if not dirs: print root

At a bottom node the dirs list from os.walk will be empty.

And you can get the list of all bottom dirs with:

leaves = [ root for (root,dirs,files) in os.walk(start) if not dirs]

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld





More information about the Tutor mailing list