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 | |
| 9 | cache = {} |
| 10 | |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 11 | def listdir(path): |
| 12 | """List directory contents, using cache.""" |
| 13 | try: |
| 14 | cached_mtime, list = cache[path] |
| 15 | del cache[path] |
| 16 | except KeyError: |
| 17 | cached_mtime, list = -1, [] |
| 18 | try: |
| 19 | mtime = os.stat(path)[8] |
| 20 | except os.error: |
| 21 | return [] |
| 22 | if mtime <> cached_mtime: |
| 23 | try: |
| 24 | list = os.listdir(path) |
| 25 | except os.error: |
| 26 | return [] |
| 27 | list.sort() |
| 28 | cache[path] = mtime, list |
| 29 | return list |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 30 | |
| 31 | opendir = listdir # XXX backward compatibility |
| 32 | |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 33 | def annotate(head, list): |
| 34 | """Add '/' suffixes to directories.""" |
| 35 | for i in range(len(list)): |
| 36 | if os.path.isdir(os.path.join(head, list[i])): |
| 37 | list[i] = list[i] + '/' |