Quick update to the README file. For intros and books we now point to
[python/dscho.git] / Lib / glob.py
blob599d41b5e12ccbf324cbf0284dac3e9b3a63188e
1 """Filename globbing utility."""
3 import os
4 import fnmatch
5 import re
8 def glob(pathname):
9 """Return a list of paths matching a pathname pattern.
11 The pattern may contain simple shell-style wildcards a la fnmatch.
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
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
53 magic_check = re.compile('[*?[]')
55 def has_magic(s):
56 return magic_check.search(s) is not None