home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / DIRCACHE.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  1014 b   |  38 lines

  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."""
  6.  
  7. import os
  8.  
  9. cache = {}
  10.  
  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
  30.  
  31. opendir = listdir # XXX backward compatibility
  32.  
  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] + '/'
  38.