Listing only directories?
Jp Calderone
exarkun at intarweb.us
Mon Jun 2 06:19:48 EDT 2003
On Mon, Jun 02, 2003 at 08:11:39PM +1000, Andrew Bennetts wrote:
> On Mon, Jun 02, 2003 at 11:01:55AM +0100, Richard wrote:
> > Hi,
> >
> > I am using os.listdir(root) to get a file and directory listing of the
> > 'root' directory. However I am trying to filter out only the directories in
> > this listing.
> >
> > I have tried the following (after reading up in the manual):
> >
> > def listDirectories(root):
> > [f for f in os.listdir(root) if os.path.isdir(f)]
> > return f
> >
> > but this doesn't seem to do what I want it to, only seeming to return the
> > name of one of the directories it finds.
>
> That's because you're only returning one thing <wink>
>
> > Can anyone tell me what I am doing wrong, and if I'm barking up completely
> > the wrong tree?
>
> I think you meant:
>
> def listDirectories(root):
> return [f for f in os.listdir(root) if os.path.isdir(f)]
Or rather,
def listDirectories(root):
d = os.path.listdir(root)
return [f for f in d if os.path.isdir(os.path.join(root, f))]
Or possibly
def listDirectories(root):
d = [os.path.join(root, f) for f in os.listdir(root)]
return [f for f in d if os.path.isdir(f)]
depending on whether you want 'root/dir' or simply 'dir' in your output.
Jp
--
Seduced, shaggy Samson snored.
She scissored short. Sorely shorn,
Soon shackled slave, Samson sighed,
Silently scheming,
Sightlessly seeking
Some savage, spectacular suicide.
-- Stanislaw Lem, "Cyberiad"
More information about the Python-list
mailing list