[Tutor] bash find equivalent in Python
Scott Widney
SWidney@ci.las-vegas.nv.us
Fri Jul 11 20:09:02 2003
> On Fri, 11 Jul 2003, Scott Widney wrote:
>
> > > def subdirs(root, skip_symlinks = 1):
> > > """Given a root directory, returns the first-level
> > > subdirectories."""
> > > try:
> > > dirs = [os.path.join(root, x)
> > > for x in os.listdir(root)]
> > > dirs = filter(os.path.isdir, dirs)
> >
> > I'm thinking that these two steps can be condensed into one:
> >
> > dirs = [os.path.join(root, x)
> > for x in os.listdir(root)
> > if os.path.isdir(x)]
>
> Hi Scott,
>
> This almost works. *grin* We have to do the os.path.join()ing
> thing when we check if it's a directory:
>
>
> dirs = [os.path.join(root, x)
> for x in os.listdir(root)
> if os.path.isdir(os.path.join(root, x))]
>
> But this looked a little too ugly, so that's why I broke it
> down into two steps.
>
>
> Is it ok to forward this to Tutor as well?
>
>
> Talk to you later!
>
Ah yes. You're right, why type something twice in such close vicinity? I
don't have an interactive prompt right now to test this:
dirs = filter(os.path.isdir, [os.path.join(root, x)
for x in os.listdir(root)])
Will Python eval the list comprehension before or during the filter? If it
were to yield the list and filter at the same time, it would fairly fly....