home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / glob.py < prev    next >
Text File  |  1997-10-22  |  1KB  |  57 lines

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