Get all subdirs

F

Florian Lindner

Hello,
how can I get all subdirectories of a given directory. os.listdir(dir)
doesn't differentiate between directories and files, os.walk seems to me a
bit overkill since it also descends in the subdirs.
Thx,
Florian
 
L

Leif K-Brooks

Florian said:
how can I get all subdirectories of a given directory
.... return [filename for filename in os.listdir(dir)
.... if os.path.isdir(os.path.join(dir, filename))]
....['foo', 'bar', 'baz']
 
P

Peter Kleiweg

Florian Lindner schreef:
Hello,
how can I get all subdirectories of a given directory. os.listdir(dir)
doesn't differentiate between directories and files, os.walk seems to me a
bit overkill since it also descends in the subdirs.

#!/usr/bin/env python

import os

dir = '.' # '.' is current directory

for i in os.listdir(dir):
if os.path.isdir(os.path.join(dir, i)):
print i


Bby the way, on Linux, I noticed that the directories '.' and
'..' are not returned by os.listdir
 
G

George Yoshida

Florian said:
Hello,
how can I get all subdirectories of a given directory. os.listdir(dir)
doesn't differentiate between directories and files, os.walk seems to me a
bit overkill since it also descends in the subdirs.
Thx,
Florian

What about testing return values of os.listdir with os.path.isdir?
e.g.,

filter(os.path.isdir, os.listdir(dir))

or if you don't like high-order functions,

[filename for filename in os.listdir(dir) if os.path.isdir(filename)]
 
S

Stephen Boulet

Florian said:
Hello,
how can I get all subdirectories of a given directory. os.listdir(dir)
doesn't differentiate between directories and files, os.walk seems to me a
bit overkill since it also descends in the subdirs.
Thx,
Florian

I'm a fan of the path module:

from path import path

p = path("my_directory")
l = [i.name for i in p.dirs()]

Stephen
 
T

Tim Peters

[Florian Lindner]
how can I get all subdirectories of a given directory. os.listdir(dir)
doesn't differentiate between directories and files, os.walk seems to me a
bit overkill since it also descends in the subdirs.

os.walk() is a generator -- it doesn't descend into anything unless
you resume it. That's the usual case, but you don't need to resume
it.

def subdirs(dir):
"Return list of the subdirectories of dir."
for root, dirs, files in os.walk(dir):
return dirs

works fine, or, perhaps more obscurely,

def subdirs(dir):
"Return list of the subdirectories of dir."
return os.walk(dir).next()[1]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top