views:

220

answers:

5

This link is using a custom method, but I just wanna see if there is a single method to do it in Python 2.6?

+2  A: 

If *a_directory* is the directory you want to inspect, then:

next(f[1] for f in os.walk(a_directory))

From the os.walk() reference:

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

Stephan202
+1: Though, you might want to break and not descend recursively into the subdirectories. Personally, I'd prefer calling os.listdir and os.isdir explicitly.
Pankrat
If changed the code. this will not recurse...
Stephan202
+1  A: 

I don't believe there is. Since directories are also files, you have to ask for all the files, then ask each one if it is a directory.

MStodd
+4  A: 

There isn't a built-in function to only list files, but it's easy enough to define in a couple of lines:

def listfiles(directory):
    return [f for f in os.listdir(directory) 
              if os.path.isdir(os.path.join(directory, f))]

EDIT: fixed, thanks Stephan202

dF
You mean os.path.isdir(os.path.join(directory, f)) instead of os.path.isfile(f)...
Stephan202
The question was to find only directories, not only files (which is an odd way around, I suppose)
dbr
A: 
def listdirs(path):
    ret = []
    for cur_name in os.listdir(path):
        full_path = os.path.join(path, cur_name)
        if os.path.isdir(full_path):
            ret.append(cur_name)
    return ret

onlydirs = listdir("/tmp/")
print onlydirs

..or as a list-comprehension..

path = "/tmp/"
onlydirs = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
print onlydirs
dbr
A: 

thanks dbr. it works perfectly :)

this is not a forum, please remove this non-answer
SilentGhost