Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list only down-most directories in Python?

Tags:

python

import os

for dirpaths, dirnames, filenames in os.walk(mydir):
    print dirpaths

gives me all (sub)directories in mydir. How do I get only the directories at the very bottom of the tree?

like image 966
djas Avatar asked Jul 30 '13 19:07

djas


3 Answers

This will print out only those directories that have no subdirectories within them

for dirpath, dirnames, filenames in os.walk(mydir):
    if not dirnames:
        print dirpath, "has 0 subdirectories and", len(filenames), "files"
like image 135
inspectorG4dget Avatar answered Oct 08 '22 02:10

inspectorG4dget


Like this?

for dirpaths, dirnames, filenames in os.walk(mydir):
    if not dirnames: print dirpaths
like image 21
Roman Pekar Avatar answered Oct 08 '22 03:10

Roman Pekar


import os

mydir='/home/'
print [dirpaths for dirpaths, dirnames, filenames in os.walk(mydir) if not dirnames]
like image 32
user9829782 Avatar answered Oct 08 '22 04:10

user9829782