Coverage for /Users/Dave/git_repos/_packages_/python/fundamentals/fundamentals/files/recursive_directory_listing.py : 16%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1#!/usr/local/bin/python
2# encoding: utf-8
3"""
4*List the contents of a directory recursively*
6:Author:
7 David Young
9:Date Created:
10 June 17, 2016
11"""
12################# GLOBAL IMPORTS ####################
13import sys
14import os
15os.environ['TERM'] = 'vt100'
16from fundamentals import tools
19def recursive_directory_listing(
20 log,
21 baseFolderPath,
22 whatToList="all"
23):
24 """*list directory contents recursively.*
26 Options to list only files or only directories.
28 **Key Arguments:**
29 - ``log`` -- logger
30 - ``baseFolderPath`` -- path to the base folder to list contained files and folders recursively
31 - ``whatToList`` -- list files only, durectories only or all [ "files" | "dirs" | "all" ]
33 **Return:**
34 - ``matchedPathList`` -- the matched paths
36 **Usage:**
38 .. code-block:: python
40 from fundamentals.files import recursive_directory_listing
41 theseFiles = recursive_directory_listing(
42 log,
43 baseFolderPath="/tmp"
44 )
46 # OR JUST FILE
48 from fundamentals.files import recursive_directory_listing
49 theseFiles = recursive_directory_listing(
50 log,
51 baseFolderPath="/tmp",
52 whatToList="files"
53 )
56 # OR JUST FOLDERS
58 from fundamentals.files import recursive_directory_listing
59 theseFiles = recursive_directory_listing(
60 log,
61 baseFolderPath="/tmp",
62 whatToList="dirs"
63 )
64 print theseFiles
65 """
66 log.debug('starting the ``recursive_directory_listing`` function')
68 ## VARIABLES ##
69 matchedPathList = []
70 parentDirectoryList = [baseFolderPath, ]
72 count = 0
73 while os.listdir(baseFolderPath) and count < 20:
74 count += 1
76 while len(parentDirectoryList) != 0:
77 childDirList = []
78 for parentDir in parentDirectoryList:
79 try:
80 thisDirList = os.listdir(parentDir)
81 except Exception as e:
82 log.error(e)
83 continue
85 for d in thisDirList:
86 fullPath = os.path.join(parentDir, d)
88 if whatToList is "all":
89 matched = True
90 elif whatToList is "dirs":
91 matched = os.path.isdir(fullPath)
92 elif whatToList is "files":
93 matched = os.path.isfile(fullPath)
94 else:
95 log.error(
96 'cound not list files in %s, `whatToList` variable incorrect: [ "files" | "dirs" | "all" ]' % (baseFolderPath,))
97 sys.exit(0)
99 if matched:
100 matchedPathList.append(fullPath)
102 # UPDATE DIRECTORY LISTING
103 if os.path.isdir(fullPath):
104 childDirList.append(fullPath)
106 parentDirectoryList = childDirList
108 log.debug('completed the ``recursive_directory_listing`` function')
109 return matchedPathList