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?
views:
220answers:
5
+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
2009-04-08 20:00:13
+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
2009-04-08 20:06:37
If changed the code. this will not recurse...
Stephan202
2009-04-08 20:08:46
+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
2009-04-08 20:04:18
+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
2009-04-08 20:20:44
You mean os.path.isdir(os.path.join(directory, f)) instead of os.path.isfile(f)...
Stephan202
2009-04-08 20:26:27
The question was to find only directories, not only files (which is an odd way around, I suppose)
dbr
2009-04-08 20:38:52
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
2009-04-08 20:37:21