Hide keyboard shortcuts

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* 

5 

6:Author: 

7 David Young 

8""" 

9import sys 

10import os 

11os.environ['TERM'] = 'vt100' 

12from fundamentals import tools 

13 

14 

15def recursive_directory_listing( 

16 log, 

17 baseFolderPath, 

18 whatToList="all" 

19): 

20 """*list directory contents recursively.* 

21 

22 Options to list only files or only directories. 

23 

24 **Key Arguments** 

25 

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" ] 

29 

30 

31 **Return** 

32 

33 - ``matchedPathList`` -- the matched paths 

34 

35 

36 **Usage** 

37 

38 ```python 

39 from fundamentals.files import recursive_directory_listing 

40 theseFiles = recursive_directory_listing( 

41 log, 

42 baseFolderPath="/tmp" 

43 ) 

44 

45 # OR JUST FILE  

46 

47 from fundamentals.files import recursive_directory_listing 

48 theseFiles = recursive_directory_listing( 

49 log, 

50 baseFolderPath="/tmp", 

51 whatToList="files" 

52 ) 

53 

54 # OR JUST FOLDERS  

55 

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') 

66 

67 ## VARIABLES ## 

68 matchedPathList = [] 

69 parentDirectoryList = [baseFolderPath, ] 

70 

71 count = 0 

72 while os.listdir(baseFolderPath) and count < 20: 

73 count += 1 

74 

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 

83 

84 for d in thisDirList: 

85 fullPath = os.path.join(parentDir, d) 

86 

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) 

97 

98 if matched: 

99 matchedPathList.append(fullPath) 

100 

101 # UPDATE DIRECTORY LISTING 

102 if os.path.isdir(fullPath): 

103 childDirList.append(fullPath) 

104 

105 parentDirectoryList = childDirList 

106 

107 log.debug('completed the ``recursive_directory_listing`` function') 

108 return matchedPathList