Coverage for pyguymer3/remove_almost_empty_directories.py: 4%

24 statements  

« prev     ^ index     » next       coverage.py v7.9.2, created at 2025-07-08 18:47 +0000

1#!/usr/bin/env python3 

2 

3# Define function ... 

4def remove_almost_empty_directories( 

5 path, 

6 /, 

7 *, 

8 debug = __debug__, 

9 ignorableFiles = ( 

10 ".directory", 

11 ".DS_Store", 

12 "cover.jpg", 

13 "cover.png", 

14 "Thumbs.db", 

15 "._.directory", 

16 "._.DS_Store", 

17 "._cover.jpg", 

18 "._cover.png", 

19 "._Thumbs.db", 

20 ), 

21 remove = False, 

22): 

23 """Remove directories which are almost empty. 

24 

25 This function removes directories which are *almost* empty, based on a tuple 

26 of ignorable file names. 

27 

28 Parameters 

29 ---------- 

30 path : str 

31 the directory to search 

32 debug : bool, optional 

33 print debug messages 

34 ignorableFiles : tuple of str, optional 

35 the tuple of file names which can safely be ignored 

36 remove : bool, optional 

37 remove almost empty directories 

38 

39 Returns 

40 ------- 

41 ans : int 

42 the number of removed directories 

43 

44 Notes 

45 ----- 

46 Copyright 2017 Thomas Guymer [1]_ 

47 

48 References 

49 ---------- 

50 .. [1] PyGuymer3, https://github.com/Guymer/PyGuymer3 

51 """ 

52 

53 # Import standard modules ... 

54 import os 

55 

56 # Initialize counter ... 

57 i = 0 # [#] 

58 

59 # Loop over all the contents of the passed directory ... 

60 for root, dnames, fnames in os.walk(path): 

61 # Skip this directory if there are sub-directories ... 

62 if len(dnames): 

63 continue 

64 

65 # Make a list of all of the non-ignorable files in this directory ... 

66 nonIgnorableFiles = fnames.copy() 

67 for ignorableFile in ignorableFiles: 

68 if ignorableFile in nonIgnorableFiles: 

69 nonIgnorableFiles.remove(ignorableFile) 

70 

71 # Skip this directory if there are non-ignorable files ... 

72 if len(nonIgnorableFiles): 

73 continue 

74 

75 # Increment counter ... 

76 i += 1 # [#] 

77 

78 # Remove all ignorable files ... 

79 for ignorableFile in ignorableFiles: 

80 if ignorableFile in fnames: 

81 if debug: 

82 print(f"Removing \"{root}/{ignorableFile}\" ...") 

83 if remove: 

84 os.remove(f"{root}/{ignorableFile}") 

85 

86 # Remove directory ... 

87 if debug: 

88 print(f"Removing \"{root}\" ...") 

89 if remove: 

90 os.rmdir(root) 

91 

92 # Return counter ... 

93 return i