-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdir_stats.py
More file actions
153 lines (117 loc) · 4.13 KB
/
Copy pathdir_stats.py
File metadata and controls
153 lines (117 loc) · 4.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# asucha 2026
"""
This script provides simple information about the directory and it's subdirectories' contents.
HOW TO RUN:
python3 dir_stats.py # for current directory
python3 dir_stats.py ~/Documents # for specifying a directory (supports macOS home path ~ expansions)
"""
import argparse
import os
from pathlib import Path
def get_dir_stats(path: Path):
"""Calculates total size, count of subfolders, and count of files within a directory."""
total_size = 0
file_count = 0
subfolder_count = 0
try:
for root, dirs, files in os.walk(path):
file_count += len(files)
subfolder_count += len(dirs)
for f in files:
file_path = os.path.join(root, f)
try:
# Ignore symlinks to prevent infinite loops or double-counting on Unix systems
if not os.path.islink(file_path):
total_size += os.path.getsize(file_path)
except (OSError, PermissionError):
# Gracefully skip macOS system files or protected items
continue
except (PermissionError, OSError):
pass # Skip directories where access is restricted by macOS Privacy settings
return total_size, subfolder_count, file_count
def format_size(size_in_bytes: int) -> str:
"""Formats bytes into human-readable units (KB, MB, GB, TB)."""
if size_in_bytes == 0:
return "0 B"
units = ["B", "KB", "MB", "GB", "TB"]
unit_index = 0
size = float(size_in_bytes)
while size >= 1024 and unit_index < len(units) - 1:
size /= 1024
unit_index += 1
return f"{size:.2f} {units[unit_index]}"
def analyze_directory(target_path: str):
target = Path(target_path).expanduser().resolve()
if not target.exists():
print(f"Error: Path '{target}' does not exist.")
return
if not target.is_dir():
print(f"Error: Path '{target}' is not a directory.")
return
print(f"\nAnalyzing: {target}\n" + "-" * 75)
try:
subdirs = [p for p in target.iterdir() if p.is_dir()]
except PermissionError:
print(
"Error: Permission denied. Make sure Terminal/iTerm has access permissions."
)
return
if not subdirs:
print("No subfolders found in the specified directory.")
return
folder_data = []
total_subfolders_size = 0
for sd in subdirs:
size, num_subfolders, num_files = get_dir_stats(sd)
folder_data.append(
{
"name": sd.name,
"size_bytes": size,
"num_subfolders": num_subfolders,
"num_files": num_files,
}
)
total_subfolders_size += size
# Sort largest subfolders first
folder_data.sort(key=lambda x: x["size_bytes"], reverse=True)
# Format Table Output
header_name = "Subfolder Name"
header_size = "Size"
header_share = "% Share"
header_subdirs = "Subfolders"
header_files = "Files"
print(
f"{header_name:<30} | {header_size:>10} | {header_share:>8} | {header_subdirs:>10} | {header_files:>10}"
)
print("-" * 80)
for data in folder_data:
share = (
(data["size_bytes"] / total_subfolders_size) * 100
if total_subfolders_size > 0
else 0.0
)
formatted_size = format_size(data["size_bytes"])
short_name = (
data["name"][:27] + "..."
if len(data["name"]) > 30
else data["name"]
)
print(
f"{short_name:<30} | {formatted_size:>10} | {share:>7.2f}% | {data['num_subfolders']:>10} | {data['num_files']:>10}"
)
print("-" * 80)
print(
f"Total Combined Subfolder Size: {format_size(total_subfolders_size)}"
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Aggregate subfolder usage stats."
)
parser.add_argument(
"path",
nargs="?",
default=".",
help="Target directory path (default: current directory)",
)
args = parser.parse_args()
analyze_directory(args.path)