Guido van Rossum | 4b8c6ea | 2000-02-04 15:39:30 +0000 | [diff] [blame] | 1 | """Read and cache directory listings. |
| 2 | |
| 3 | The listdir() routine returns a sorted list of the files in a directory, |
| 4 | using a cache to avoid reading the directory more often than necessary. |
| 5 | The annotate() routine appends slashes to directories.""" |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 6 | |
Guido van Rossum | c96207a | 1992-03-31 18:55:40 +0000 | [diff] [blame] | 7 | import os |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 8 | |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 9 | __all__ = ["listdir","opendir","annotate"] |
| 10 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 11 | cache = {} |
| 12 | |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 13 | def listdir(path): |
| 14 | """List directory contents, using cache.""" |
| 15 | try: |
| 16 | cached_mtime, list = cache[path] |
| 17 | del cache[path] |
| 18 | except KeyError: |
| 19 | cached_mtime, list = -1, [] |
| 20 | try: |
| 21 | mtime = os.stat(path)[8] |
| 22 | except os.error: |
| 23 | return [] |
Fred Drake | 8152d32 | 2000-12-12 23:20:45 +0000 | [diff] [blame] | 24 | if mtime != cached_mtime: |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 25 | try: |
| 26 | list = os.listdir(path) |
| 27 | except os.error: |
| 28 | return [] |
| 29 | list.sort() |
| 30 | cache[path] = mtime, list |
| 31 | return list |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 32 | |
| 33 | opendir = listdir # XXX backward compatibility |
| 34 | |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 35 | def annotate(head, list): |
| 36 | """Add '/' suffixes to directories.""" |
| 37 | for i in range(len(list)): |
| 38 | if os.path.isdir(os.path.join(head, list[i])): |
| 39 | list[i] = list[i] + '/' |