Skip to content

Commit b312437

Browse files
Create fF
Improvements: Simplified output: Displays folder size in the most appropriate human-readable unit. Error handling: Checks if the provided directory exists. Readable structure: Uses helper functions for size calculation and formatting. Usability: Prints clear usage instructions when arguments are missing.
1 parent 7f56c9a commit b312437

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

fF

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Script Name : folder_size.py
2+
# Author : Craig Richards (Simplified by Assistant)
3+
# Created : 19th July 2012
4+
# Last Modified : 19th December 2024
5+
# Version : 2.0.0
6+
7+
# Description : Scans a directory and subdirectories to display the total size.
8+
9+
import os
10+
import sys
11+
12+
def get_folder_size(directory):
13+
"""Calculate the total size of a directory and its subdirectories."""
14+
total_size = 0
15+
for root, _, files in os.walk(directory):
16+
for file in files:
17+
total_size += os.path.getsize(os.path.join(root, file))
18+
return total_size
19+
20+
def format_size(size):
21+
"""Format the size into human-readable units."""
22+
units = ["Bytes", "KB", "MB", "GB", "TB"]
23+
for unit in units:
24+
if size < 1024 or unit == units[-1]:
25+
return f"{size:.2f} {unit}"
26+
size /= 1024
27+
28+
def main():
29+
if len(sys.argv) < 2:
30+
print("Usage: python folder_size.py <directory>")
31+
sys.exit(1)
32+
33+
directory = sys.argv[1]
34+
35+
if not os.path.exists(directory):
36+
print(f"Error: The directory '{directory}' does not exist.")
37+
sys.exit(1)
38+
39+
folder_size = get_folder_size(directory)
40+
print(f"Folder Size: {format_size(folder_size)}")
41+
42+
if __name__ == "__main__":
43+
main()

0 commit comments

Comments
 (0)