|
| 1 | +import os |
| 2 | +import sys |
| 3 | + |
| 4 | +def get_folder_size(path): |
| 5 | + total_size = 0 |
| 6 | + # Walk through all directories and files inside the given path |
| 7 | + for dirpath, dirnames, filenames in os.walk(path): |
| 8 | + for f in filenames: |
| 9 | + fp = os.path.join(dirpath, f) |
| 10 | + # Check if file exists and is not a symbolic link |
| 11 | + if not os.path.islink(fp) and os.path.exists(fp): |
| 12 | + try: |
| 13 | + total_size += os.path.getsize(fp) # Add file size (in bytes) |
| 14 | + except (PermissionError, FileNotFoundError): |
| 15 | + pass |
| 16 | + return total_size |
| 17 | + |
| 18 | + |
| 19 | +def format_size(size_in_bytes): |
| 20 | + for unit in ['B', 'KB', 'MB', 'GB', 'TB']: |
| 21 | + if size_in_bytes < 1024: |
| 22 | + # Return formatted size when it fits the current unit |
| 23 | + return f"{size_in_bytes:.2f} {unit}" |
| 24 | + size_in_bytes /= 1024 |
| 25 | + return f"{size_in_bytes:.2f} PB" |
| 26 | + |
| 27 | + |
| 28 | +def main(): |
| 29 | + # Ensure a folder path is provided as command-line argument |
| 30 | + if len(sys.argv) < 2: |
| 31 | + print("Usage: python folder_size_calculator.py <folder_path>") |
| 32 | + sys.exit(1) |
| 33 | + |
| 34 | + folder_path = sys.argv[1] # Read the folder path from arguments |
| 35 | + |
| 36 | + if not os.path.exists(folder_path): |
| 37 | + print(f"Error: The path '{folder_path}' does not exist.") |
| 38 | + sys.exit(1) |
| 39 | + |
| 40 | + print(f"\nCalculating folder sizes inside: {folder_path}\n") |
| 41 | + |
| 42 | + total_size = 0 # Variable to store total folder size |
| 43 | + |
| 44 | + # Loop through everything inside the given folder |
| 45 | + for item in os.listdir(folder_path): |
| 46 | + item_path = os.path.join(folder_path, item) |
| 47 | + if os.path.isdir(item_path): |
| 48 | + size = get_folder_size(item_path) |
| 49 | + print(f"{item}/".ljust(45) + f"= {format_size(size)}") |
| 50 | + total_size += size |
| 51 | + |
| 52 | + # If the item is a file — get its direct size |
| 53 | + elif os.path.isfile(item_path): |
| 54 | + try: |
| 55 | + size = os.path.getsize(item_path) |
| 56 | + print(f"{item}".ljust(45) + f"= {format_size(size)}") |
| 57 | + total_size += size |
| 58 | + except (PermissionError, FileNotFoundError): |
| 59 | + pass |
| 60 | + |
| 61 | + # Finally, print total folder size |
| 62 | + print(f"Total size of '{folder_path}': {format_size(total_size)}") |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + main() |
0 commit comments