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
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-08 18:47 +0000
1#!/usr/bin/env python3
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.
25 This function removes directories which are *almost* empty, based on a tuple
26 of ignorable file names.
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
39 Returns
40 -------
41 ans : int
42 the number of removed directories
44 Notes
45 -----
46 Copyright 2017 Thomas Guymer [1]_
48 References
49 ----------
50 .. [1] PyGuymer3, https://github.com/Guymer/PyGuymer3
51 """
53 # Import standard modules ...
54 import os
56 # Initialize counter ...
57 i = 0 # [#]
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
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)
71 # Skip this directory if there are non-ignorable files ...
72 if len(nonIgnorableFiles):
73 continue
75 # Increment counter ...
76 i += 1 # [#]
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}")
86 # Remove directory ...
87 if debug:
88 print(f"Removing \"{root}\" ...")
89 if remove:
90 os.rmdir(root)
92 # Return counter ...
93 return i