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

Jeremy C B Nicoll jeremy at omba.demon.co.uk
Wed Aug 15 13:34:27 CEST 2007

Jeremy C B Nicoll <jernic at blueyonder.co.uk> wrote:
> When I use os.listdir() to return that list of leaf values, I do seem to
> get them in alphabetical order, A before B before C etc, but the
> ~-prefixed ones are returned after the Z-prefixed files rather than before
> the A-ones.

Thanks to people who replied here, and by email.

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:

How would I sort leaflist in a way that mimics the sort order that XP shows
me things under?  

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?

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?

Jeremy C B Nicoll - my opinions are my own.

More information about the Python-list mailing list