[Python-ideas] Add OS-dependent automatic glob support

Steven D'Aprano steve at pearwood.info
Tue Jan 6 00:57:10 CET 2015

On Tue, Jan 06, 2015 at 04:14:38AM +1100, Chris Angelico wrote:
> On Tue, Jan 6, 2015 at 4:10 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> > * If you want to apply globs to something other than file names,
> >   the right module to use would probably be globbing.generic
> >   (or possible fnmatch directly).
> To clarify: Do you mean "something other than names of
> currently-existing files", or "something other than valid names for
> the local file system", or something else? For instance, suppose you
> write an unarchiver (in case we don't have enough of them already, of
> course), and you can "python unarchive.py archivename *.txt" to
> extract all files matching *.txt. The globbing would be done against
> some sort of internal index, but the names would have to be valid for
> the local file system, or you wouldn't be able to create them. Which
> module should you use?

fnmatch. I've had a look inside glob.py and it calls os.listdir 
directly, so you cannot use glob to match things other than actual 
existing files. (Well, I suppose you could if you monkey-patched the 
module, but lets not go there.)

fnmatch, on the other hand, provides the right tool for matching names
other than actual file names: fnmatch.filter(names, pattern). (Well, 
almost the right tool -- it has a few issues too.)

To summarise:

- the glob module returns only actual files in the file system;
- the new globbing package will do the same, except it will 
  use platform-specific wildcards where possible;
- fnmatch continues as Python's generic "match globs against 
  arbitrary strings" module (despite the name).


More information about the Python-ideas mailing list