Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame^] | 1 | """Return a sorted list of the files in a directory, using a cache |
| 2 | to avoid reading the directory more often than necessary. |
| 3 | Also contains a subroutine to append slashes to directories.""" |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 4 | |
Guido van Rossum | c96207a | 1992-03-31 18:55:40 +0000 | [diff] [blame] | 5 | import os |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 6 | |
| 7 | cache = {} |
| 8 | |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame^] | 9 | def listdir(path): |
| 10 | """List directory contents, using cache.""" |
| 11 | try: |
| 12 | cached_mtime, list = cache[path] |
| 13 | del cache[path] |
| 14 | except KeyError: |
| 15 | cached_mtime, list = -1, [] |
| 16 | try: |
| 17 | mtime = os.stat(path)[8] |
| 18 | except os.error: |
| 19 | return [] |
| 20 | if mtime <> cached_mtime: |
| 21 | try: |
| 22 | list = os.listdir(path) |
| 23 | except os.error: |
| 24 | return [] |
| 25 | list.sort() |
| 26 | cache[path] = mtime, list |
| 27 | return list |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 28 | |
| 29 | opendir = listdir # XXX backward compatibility |
| 30 | |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame^] | 31 | def annotate(head, list): |
| 32 | """Add '/' suffixes to directories.""" |
| 33 | for i in range(len(list)): |
| 34 | if os.path.isdir(os.path.join(head, list[i])): |
| 35 | list[i] = list[i] + '/' |