Source

"""Read and cache directory listings.The listdir() routine returns a sorted list of the files in a directory,using a cache to avoid reading the directory more often than necessary.The annotate() routine appends slashes to directories."""importos__all__=["listdir","opendir","annotate","reset"]cache={}defreset():"""Reset the cache completely."""globalcachecache={}deflistdir(path):"""List directory contents, using cache."""try:cached_mtime,list=cache[path]delcache[path]exceptKeyError:cached_mtime,list=-1,[]try:mtime=os.stat(path).st_mtimeexceptos.error:return[]ifmtime!=cached_mtime:try:list=os.listdir(path)exceptos.error:return[]list.sort()cache[path]=mtime,listreturnlistopendir=listdir# XXX backward compatibilitydefannotate(head,list):"""Add '/' suffixes to directories."""foriinrange(len(list)):ifos.path.isdir(os.path.join(head,list[i])):list[i]=list[i]+'/'