blob: a35e16d1bc6ad5366e9c84c04fb47c1f0ca98f3c [file] [log] [blame]
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00001"""Read and cache directory listings.
2
3The listdir() routine returns a sorted list of the files in a directory,
4using a cache to avoid reading the directory more often than necessary.
5The annotate() routine appends slashes to directories."""
Guido van Rossumc6360141990-10-13 19:23:40 +00006
Guido van Rossumc96207a1992-03-31 18:55:40 +00007import os
Guido van Rossumc6360141990-10-13 19:23:40 +00008
9cache = {}
10
Guido van Rossum4acc25b2000-02-02 15:10:15 +000011def 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 Rossumc6360141990-10-13 19:23:40 +000030
31opendir = listdir # XXX backward compatibility
32
Guido van Rossum4acc25b2000-02-02 15:10:15 +000033def 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] + '/'