Search code examples
pythonlistdirectorypathrelative-path

How to get the list of dirs from a path that is provided as input, in Python using os.walk


I have a directory "a" whcih has 5 sub dirs a1 through a5 in it. All that I want is if I gave a "path" as input to a script, I want the list of directories in that path. For instance here if I had said "path=/home/abc/a" the output should be a1 through a5.

The o/p using os.walk is slightly different than what I want..how do I get it?

>>> import os
    >>> for dirs in os.walk("."):
    ...     print "Name", dirs
    ... 
    Name ('.', ['a1', 'a2', 'a3', 'a4', 'a5'], [])
    Name ('./a1', [], [])
    Name ('./a2', [], [])
    Name ('./a3', [], [])
    Name ('./a4', [], [])
    Name ('./a5', [], [])

Solution

  • I'm not sure what you're asking for...all the sub directories in that directory? Try this

    os.walk("path").next()[1]
    

    Edit: Should have explained a bit. As Chris mentions, os.walk() will return a generator object, and the next() method retrieves the next item from this object. Since this is a 3-tuple consisting of (root, dirs, files) and you only want sub directories, you only need to index into the relevant part.