0

This is the directory structure

10
  files
    2009
    2010
11
  files
    2007
    2010
    2006

I am trying to get full path names of all the directories inside files

import os
x = os.walk('.').next()[1]

print x # prints ['33', '18', '27', '39', '2', '62', '25']

for a in x:
    y = os.walk(a).next()[1]

print y # prints ['files']

I tried a nested for but getting stopiteration error.

What I am intending to do is get something like below,

['10/files/2009','10/files/2010','11/files/2007','11/files/2010','10/files/2006']

How to do it in python?

1 Answer 1

2

It looks like you want only the most deeply nested directories. If you use the topdown=False parameter you'll get a depth-first traversal, which will list the most deeply nested directories before their parent directories.

To filter out higher level directories, you could use a set to keep track of parent directories so as to omit reporting those:

import os

def listdirs(path):
    seen = set()
    for root, dirs, files in os.walk(path, topdown=False):
        if dirs:
            parent = root
            while parent:
                seen.add(parent)
                parent = os.path.dirname(parent)
        for d in dirs:
            d = os.path.join(root, d)
            if d not in seen:
                yield d

for d in listdirs('.'):
    print(d)
Sign up to request clarification or add additional context in comments.

1 Comment

Why the topdown=False?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.