blob: 354af390a780ed961d70334b0f6b068816a9cd4c [file] [log] [blame]
Guido van Rossum65a96201991-01-01 18:17:49 +00001# Module 'glob' -- filename globbing.
2
Guido van Rossumbba77af1992-01-12 23:26:24 +00003import os
Guido van Rossum65a96201991-01-01 18:17:49 +00004import fnmatch
5
Guido van Rossumbba77af1992-01-12 23:26:24 +00006
Guido van Rossum65a96201991-01-01 18:17:49 +00007def glob(pathname):
8 if not has_magic(pathname): return [pathname]
Guido van Rossumbba77af1992-01-12 23:26:24 +00009 dirname, basename = os.path.split(pathname)
Guido van Rossum65a96201991-01-01 18:17:49 +000010 if has_magic(dirname):
11 list = glob(dirname)
12 else:
13 list = [dirname]
14 if not has_magic(basename):
15 result = []
16 for dirname in list:
Guido van Rossumbba77af1992-01-12 23:26:24 +000017 if basename or os.path.isdir(dirname):
18 name = os.path.join(dirname, basename)
19 if os.path.exists(name):
Guido van Rossum65a96201991-01-01 18:17:49 +000020 result.append(name)
21 else:
22 result = []
23 for dirname in list:
24 sublist = glob1(dirname, basename)
25 for name in sublist:
Guido van Rossumbba77af1992-01-12 23:26:24 +000026 result.append(os.path.join(dirname, name))
Guido van Rossum65a96201991-01-01 18:17:49 +000027 return result
28
29def glob1(dirname, pattern):
Guido van Rossumbba77af1992-01-12 23:26:24 +000030 if not dirname: dirname = os.curdir
Guido van Rossum65a96201991-01-01 18:17:49 +000031 try:
Guido van Rossumbba77af1992-01-12 23:26:24 +000032 names = os.listdir(dirname)
33 except os.error:
Guido van Rossum65a96201991-01-01 18:17:49 +000034 return []
35 result = []
36 for name in names:
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000037 if name[0] <> '.' or pattern[0] == '.':
Guido van Rossum65a96201991-01-01 18:17:49 +000038 if fnmatch.fnmatch(name, pattern): result.append(name)
39 return result
40
41def has_magic(s):
42 return '*' in s or '?' in s or '[' in s