What order does info get returned in by os.listdir()

Jeremy C B Nicoll jeremy at omba.demon.co.uk
Wed Aug 15 15:33:51 CEST 2007

Marc 'BlackJack' Rintsch <bj_666 at gmx.net> wrote:

> On Wed, 15 Aug 2007 12:34:27 +0100, Jeremy C B Nicoll wrote:
> > I've some supplementary questions... my original code was looking at
> > each leafname in turn via
> > 
> >   for leaf in os.listdir(path):
> >       wholefile = os.path.join(path,leaf)
> >       if os.path.isfile(wholefile):
> >          if leaf.startswith("~"):
> > 
> > etc.  But I now realise I might alternatively do something like:
> > 
> >   leaflist = os.listdir(path)
> >   <then something to sort that list>
> >   for leaf in leaflist:
> But this is doing something different that the above code!?

I'm not sure if I understand you.  I know it's only "equivalent" to the
first line of what's above, ie iterate over a list of names, and obviously
it's got the sorting of that list done, but do you mean there's some other

> > How would I sort leaflist in a way that mimics the sort order that XP
> > shows me things under?
> This depends on what XP is.  Which program?  Which locale?  How does the
> locale influence that programs sorting?

Well... XP is Windows XP (Pro as I think I said earlier), and I'm in the UK.
I explained earlier how XP shows me stuff in order when I tell it to sort by

> > Secondly, my code is wasting time looking at subdirectories/files which
> > I already know I'm not interested in.  Is there a way to restrict
> > listdir to, say, only return info about subdirectories, or only about
> > dirs/files whose names match a pattern?
> `os.listdir()` always returns all names.  You can or have to  filter the
> result if you are only interested in some of the names.  Simple pattern
> matching on names can be done with `glob.glob()`.
> > Thirdly, once I've go a list of leafnames, somehow, is there a way to
> > ask Python if a specific leaf-value is in that list, without explicitly
> > looping through the items in the list?
> With the ``in`` operator you have an implicit loop over the list.
>   if 'readme.txt' in leafnames:
>       print 'Hurray!'

OK, that looks useful.  Thanks.

Jeremy C B Nicoll - my opinions are my own.

More information about the Python-list mailing list