Listing only directories?
Mon Jun 2 06:23:00 EDT 2003
In article <3edb2094$1 at mail.hmgcc.gov.uk>, richardd at hmgcc.gov.uk (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.
>
> Can anyone tell me what I am doing wrong, and if I'm barking up completely
> the wrong tree?
>
> Cheers
>
> Richard D
You're nearly there. You want to return the list, but you're actually
returning 'f' which, as you say, is set to one of the directories. You
should return the list directly or assign it a variable and return that.
def listDirectories1(root):
# assigning 'f' is confusing, but works
f = [f for f in os.listdir(root) if os.path.isdir(f)]
return f
def listDirectories2(root):
# assigning 'g' is easier, but unnecessary
g = [f for f in os.listdir(root) if os.path.isdir(f)]
return g
def listDirectories3(root):
return [f for f in os.listdir(root) if os.path.isdir(f)]
HTH
Martin
More information about the Python-list
mailing list