Guido van Rossum | 65a9620 | 1991-01-01 18:17:49 +0000 | [diff] [blame] | 1 | # Module 'glob' -- filename globbing. |
| 2 | |
Guido van Rossum | bba77af | 1992-01-12 23:26:24 +0000 | [diff] [blame] | 3 | import os |
Guido van Rossum | 65a9620 | 1991-01-01 18:17:49 +0000 | [diff] [blame] | 4 | import fnmatch |
| 5 | |
Guido van Rossum | bba77af | 1992-01-12 23:26:24 +0000 | [diff] [blame] | 6 | |
Guido van Rossum | 65a9620 | 1991-01-01 18:17:49 +0000 | [diff] [blame] | 7 | def glob(pathname): |
| 8 | if not has_magic(pathname): return [pathname] |
Guido van Rossum | bba77af | 1992-01-12 23:26:24 +0000 | [diff] [blame] | 9 | dirname, basename = os.path.split(pathname) |
Guido van Rossum | 65a9620 | 1991-01-01 18:17:49 +0000 | [diff] [blame] | 10 | 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 Rossum | bba77af | 1992-01-12 23:26:24 +0000 | [diff] [blame] | 17 | if basename or os.path.isdir(dirname): |
| 18 | name = os.path.join(dirname, basename) |
| 19 | if os.path.exists(name): |
Guido van Rossum | 65a9620 | 1991-01-01 18:17:49 +0000 | [diff] [blame] | 20 | result.append(name) |
| 21 | else: |
| 22 | result = [] |
| 23 | for dirname in list: |
| 24 | sublist = glob1(dirname, basename) |
| 25 | for name in sublist: |
Guido van Rossum | bba77af | 1992-01-12 23:26:24 +0000 | [diff] [blame] | 26 | result.append(os.path.join(dirname, name)) |
Guido van Rossum | 65a9620 | 1991-01-01 18:17:49 +0000 | [diff] [blame] | 27 | return result |
| 28 | |
| 29 | def glob1(dirname, pattern): |
Guido van Rossum | bba77af | 1992-01-12 23:26:24 +0000 | [diff] [blame] | 30 | if not dirname: dirname = os.curdir |
Guido van Rossum | 65a9620 | 1991-01-01 18:17:49 +0000 | [diff] [blame] | 31 | try: |
Guido van Rossum | bba77af | 1992-01-12 23:26:24 +0000 | [diff] [blame] | 32 | names = os.listdir(dirname) |
| 33 | except os.error: |
Guido van Rossum | 65a9620 | 1991-01-01 18:17:49 +0000 | [diff] [blame] | 34 | return [] |
| 35 | result = [] |
| 36 | for name in names: |
Guido van Rossum | bdfcfcc | 1992-01-01 19:35:13 +0000 | [diff] [blame] | 37 | if name[0] <> '.' or pattern[0] == '.': |
Guido van Rossum | 65a9620 | 1991-01-01 18:17:49 +0000 | [diff] [blame] | 38 | if fnmatch.fnmatch(name, pattern): result.append(name) |
| 39 | return result |
| 40 | |
| 41 | def has_magic(s): |
| 42 | return '*' in s or '?' in s or '[' in s |