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

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Aug 15 09:22:56 EDT 2007


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!?

> 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?

> 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!'

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list