-
Notifications
You must be signed in to change notification settings - Fork 12.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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.
- Loading branch information
1 parent
7f56c9a
commit b312437
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
# Script Name : folder_size.py | ||
# Author : Craig Richards (Simplified by Assistant) | ||
# Created : 19th July 2012 | ||
# Last Modified : 19th December 2024 | ||
# Version : 2.0.0 | ||
|
||
# Description : Scans a directory and subdirectories to display the total size. | ||
|
||
import os | ||
import sys | ||
|
||
def get_folder_size(directory): | ||
"""Calculate the total size of a directory and its subdirectories.""" | ||
total_size = 0 | ||
for root, _, files in os.walk(directory): | ||
for file in files: | ||
total_size += os.path.getsize(os.path.join(root, file)) | ||
return total_size | ||
|
||
def format_size(size): | ||
"""Format the size into human-readable units.""" | ||
units = ["Bytes", "KB", "MB", "GB", "TB"] | ||
for unit in units: | ||
if size < 1024 or unit == units[-1]: | ||
return f"{size:.2f} {unit}" | ||
size /= 1024 | ||
|
||
def main(): | ||
if len(sys.argv) < 2: | ||
print("Usage: python folder_size.py <directory>") | ||
sys.exit(1) | ||
|
||
directory = sys.argv[1] | ||
|
||
if not os.path.exists(directory): | ||
print(f"Error: The directory '{directory}' does not exist.") | ||
sys.exit(1) | ||
|
||
folder_size = get_folder_size(directory) | ||
print(f"Folder Size: {format_size(folder_size)}") | ||
|
||
if __name__ == "__main__": | ||
main() |