Reputation: 2001
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?
Upvotes: 0
Views: 2979
Reputation: 879251
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)
Upvotes: 2