home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_Lib_glob.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  1.5 KB  |  58 lines

  1. """Filename globbing utility."""
  2.  
  3. import os
  4. import fnmatch
  5. import re
  6.  
  7. __all__ = ["glob"]
  8.  
  9. def glob(pathname):
  10.     """Return a list of paths matching a pathname pattern.
  11.  
  12.     The pattern may contain simple shell-style wildcards a la fnmatch.
  13.  
  14.     """
  15.     if not has_magic(pathname):
  16.         if os.path.exists(pathname):
  17.             return [pathname]
  18.         else:
  19.             return []
  20.     dirname, basename = os.path.split(pathname)
  21.     if has_magic(dirname):
  22.         list = glob(dirname)
  23.     else:
  24.         list = [dirname]
  25.     if not has_magic(basename):
  26.         result = []
  27.         for dirname in list:
  28.             if basename or os.path.isdir(dirname):
  29.                 name = os.path.join(dirname, basename)
  30.                 if os.path.exists(name):
  31.                     result.append(name)
  32.     else:
  33.         result = []
  34.         for dirname in list:
  35.             sublist = glob1(dirname, basename)
  36.             for name in sublist:
  37.                 result.append(os.path.join(dirname, name))
  38.     return result
  39.  
  40. def glob1(dirname, pattern):
  41.     if not dirname: dirname = os.curdir
  42.     try:
  43.         names = os.listdir(dirname)
  44.     except os.error:
  45.         return []
  46.     result = []
  47.     for name in names:
  48.         if name[0] != '.' or pattern[0] == '.':
  49.             if fnmatch.fnmatch(name, pattern):
  50.                 result.append(name)
  51.     return result
  52.  
  53.  
  54. magic_check = re.compile('[*?[]')
  55.  
  56. def has_magic(s):
  57.     return magic_check.search(s) is not None
  58.