Files for 2.1b1 distribution.
[python/dscho.git] / Lib / glob.py
blobeeb6bdd6468aeaaa0a20fdaa6850eb2a9099b5c6
1 """Filename globbing utility."""
3 import os
4 import fnmatch
5 import re
7 __all__ = ["glob"]
9 def glob(pathname):
10 """Return a list of paths matching a pathname pattern.
12 The pattern may contain simple shell-style wildcards a la fnmatch.
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
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
54 magic_check = re.compile('[*?[]')
56 def has_magic(s):
57 return magic_check.search(s) is not None