Coverage for fundamentals/files/recursive_directory_listing.py : 0%

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
8"""
9import sys
10import os
11os.environ['TERM'] = 'vt100'
12from fundamentals import tools
15def recursive_directory_listing(
16 log,
17 baseFolderPath,
18 whatToList="all"
19):
20 """*list directory contents recursively.*
22 Options to list only files or only directories.
24 **Key Arguments**
26 - ``log`` -- logger
27 - ``baseFolderPath`` -- path to the base folder to list contained files and folders recursively
28 - ``whatToList`` -- list files only, durectories only or all [ "files" | "dirs" | "all" ]
31 **Return**
33 - ``matchedPathList`` -- the matched paths
36 **Usage**
38 ```python
39 from fundamentals.files import recursive_directory_listing
40 theseFiles = recursive_directory_listing(
41 log,
42 baseFolderPath="/tmp"
43 )
45 # OR JUST FILE
47 from fundamentals.files import recursive_directory_listing
48 theseFiles = recursive_directory_listing(
49 log,
50 baseFolderPath="/tmp",
51 whatToList="files"
52 )
54 # OR JUST FOLDERS
56 from fundamentals.files import recursive_directory_listing
57 theseFiles = recursive_directory_listing(
58 log,
59 baseFolderPath="/tmp",
60 whatToList="dirs"
61 )
62 print theseFiles
63 ```
64 """
65 log.debug('starting the ``recursive_directory_listing`` function')
67 ## VARIABLES ##
68 matchedPathList = []
69 parentDirectoryList = [baseFolderPath, ]
71 count = 0
72 while os.listdir(baseFolderPath) and count < 20:
73 count += 1
75 while len(parentDirectoryList) != 0:
76 childDirList = []
77 for parentDir in parentDirectoryList:
78 try:
79 thisDirList = os.listdir(parentDir)
80 except Exception as e:
81 log.error(e)
82 continue
84 for d in thisDirList:
85 fullPath = os.path.join(parentDir, d)
87 if whatToList == "all":
88 matched = True
89 elif whatToList == "dirs":
90 matched = os.path.isdir(fullPath)
91 elif whatToList == "files":
92 matched = os.path.isfile(fullPath)
93 else:
94 log.error(
95 'cound not list files in %s, `whatToList` variable incorrect: [ "files" | "dirs" | "all" ]' % (baseFolderPath,))
96 sys.exit(0)
98 if matched:
99 matchedPathList.append(fullPath)
101 # UPDATE DIRECTORY LISTING
102 if os.path.isdir(fullPath):
103 childDirList.append(fullPath)
105 parentDirectoryList = childDirList
107 log.debug('completed the ``recursive_directory_listing`` function')
108 return matchedPathList