cpython/Lib/dircache.py

36 lines
823 B
Python
Raw Normal View History

1990-10-14 03:23:40 +08:00
# Module 'dircache'
#
1992-04-01 02:55:40 +08:00
# Return a sorted list of the files in a directory, using a cache
1990-10-14 03:23:40 +08:00
# to avoid reading the directory more often than necessary.
# Also contains a subroutine to append slashes to directories.
1992-04-01 02:55:40 +08:00
import os
1990-10-14 03:23:40 +08:00
cache = {}
def listdir(path): # List directory contents, using cache
try:
cached_mtime, list = cache[path]
del cache[path]
1991-12-26 21:03:14 +08:00
except KeyError:
1990-10-14 03:23:40 +08:00
cached_mtime, list = -1, []
try:
1992-04-01 02:55:40 +08:00
mtime = os.stat(path)[8]
except os.error:
1990-10-14 03:23:40 +08:00
return []
if mtime <> cached_mtime:
try:
1992-04-01 02:55:40 +08:00
list = os.listdir(path)
except os.error:
1990-10-14 03:23:40 +08:00
return []
list.sort()
cache[path] = mtime, list
return list
opendir = listdir # XXX backward compatibility
def annotate(head, list): # Add '/' suffixes to directories
for i in range(len(list)):
1992-04-01 02:55:40 +08:00
if os.path.isdir(os.path.join(head, list[i])):
1990-10-14 03:23:40 +08:00
list[i] = list[i] + '/'