Conceptualizing the Python Tool
I'm now zeroing in on the core functionality. My focus is on the program's primary objective: to construct a Python CLI tool. I'm visualizing the need for directory traversal, file size calculations, and the presentation of disk usage data. This necessitates careful planning of the user interface and data handling.
Mapping Out Implementation Steps
I'm presently building the essential functionality, with conversion utilities as my starting point. Bytes-to-human-readable size conversions are my first priority. I intend to integrate a directory scanner using os.walk or the more efficient scandir. I'm giving thought to selecting the optimal data structures for presenting the results.
Outlining Core Tool Design
I've sketched out the initial code structure and am now deliberating on the data presentation. A two-pronged output approach appears optimal: a straightforward summary of overall directory size and a display of the largest files. I'm focusing on user experience, determining which format (tabular or tree-like) best conveys the information.
Structuring the Code and Features
I am constructing a class, the DiskAnalyzer, to encapsulate all the core operations, enhancing code organization. This includes methods for scanning directories, identifying the largest files, and calculating total sizes. I am also currently working on the argument parsing using argparse. Error handling is also being implemented.
Developing Core Tool Functionality
I'm deep in the implementation now, and I've created the DiskAnalyzer class, with core methods ready for implementation. I've successfully incorporated argparse for command-line argument parsing and begun writing the file size conversion utility. The structure is now defined, and I'm focused on the directory-scanning logic.
Designing the Output Format
I'm now contemplating how to present the data effectively, specifically the output format. I'm leaning toward a tabular format for the top files to ensure clarity and easy readability. Simultaneously, a tree-like view for directory structure breakdown is being considered to give a visual representation of disk usage, ensuring user accessibility.
\n\n
I am experimenting with the visual presentation to clarify the tool's output. A balance of concise file listings and the directory summary views is prioritized. I'm exploring ANSI escape codes for basic formatting, but thinking of deferring color or more complex formatting to a later enhancement stage. My objective is to create a clean, functional display.
Here is a complete, robust, and dependency-free Python CLI tool to analyze disk usage. It uses the standard library, so you don't need to install anything like pandas or click.
I will call this tool pydu (Python Disk Usage).
Features
- Human-Readable Sizes: Converts bytes to KB, MB, GB, TB.
- Sub-folder Breakdown: Shows the size of immediate subdirectories with a visual usage bar.
- Top Large Files: Identifies the largest individual files within the entire tree.
- Error Handling: Gracefully handles
PermissionDenied errors.
The Python Script (pydu.py)
Save the following code into a file named pydu.py.
#!/usr/bin/env python3
import os
import sys
import argparse
import shutil
# --- Helper Functions ---
def get_size_format(b, factor=1024, suffix="B"):
"""
Scale bytes to its proper byte format
e.g:
1253656678 => '1.17GB'
1253656 => '1.20MB'
"""
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if b < factor:
return f"{b:.2f}{unit}{suffix}"
b /= factor
return f"{b:.2f}Y{suffix}"
def get_directory_stats(path):
"""
Recursively calculates the total size of a directory.
Returns tuple: (total_size, list_of_all_files_with_sizes)
"""
total_size = 0
all_files = []
try:
# os.scandir is faster than os.walk for simple traversals
for entry in os.scandir(path):
try:
if entry.is_file(follow_symlinks=False):
size = entry.stat().st_size
total_size += size
all_files.append((entry.path, size))
elif entry.is_dir(follow_symlinks=False):
dir_size, dir_files = get_directory_stats(entry.path)
total_size += dir_size
all_files.extend(dir_files)
except (PermissionError, OSError):
# Skip files/folders we can't access
continue
except (PermissionError, OSError):
return 0, []
return total_size, all_files
def draw_bar(percent, length=20):
"""Generates a simple ASCII progress bar"""
fill = int(length * percent / 100)
bar = '█' * fill + '-' * (length - fill)
return f"[{bar}]"
# --- Main Analysis Logic ---
def analyze_disk(path, top_n=10):
abs_path = os.path.abspath(path)
if not os.path.exists(abs_path):
print(f"Error: The path '{abs_path}' does not exist.")
return
print(f"Scanning: {abs_path} ... (this may take a moment for large drives)")
print("-" * 60)
# 1. Get distinct immediate children for the "Folder Breakdown"
items = []
grand_total = 0
all_files_flat = [] # To store every file in the tree for the "Top Files" check
try:
with os.scandir(abs_path) as it:
for entry in it:
try:
if entry.is_file(follow_symlinks=False):
size = entry.stat().st_size
grand_total += size
items.append({'name': entry.name, 'size': size, 'type': 'File'})
all_files_flat.append((entry.path, size))
elif entry.is_dir(follow_symlinks=False):
# Recursively get size of subfolder
size, sub_files = get_directory_stats(entry.path)
grand_total += size
items.append({'name': entry.name, 'size': size, 'type': 'Dir'})
all_files_flat.extend(sub_files)
except (PermissionError, OSError):
continue
except PermissionError:
print(f"Permission Denied: Cannot read '{abs_path}'")
return
# Sort items by size (Descending)
items.sort(key=lambda x: x['size'], reverse=True)
# Sort all files flat list for top N
all_files_flat.sort(key=lambda x: x[1], reverse=True)
# --- Output Generation ---
print(f"\nSummary for: {abs_path}")
print(f"Total Size: \033[1;32m{get_size_format(grand_total)}\033[0m")
print(f"Total Files: {len(all_files_flat)}")
print("=" * 70)
# Use terminal columns to format nicely
cols, _ = shutil.get_terminal_size()
name_col_width = min(30, cols - 40)
print(f"{'Name':<{name_col_width}} | {'Type':<4} | {'Size':>10} | {'Usage':<20}")
print("-" * 70)
# Print Immediate Children Breakdown
for item in items:
percent = (item['size'] / grand_total * 100) if grand_total > 0 else 0
name = item['name']
if len(name) > name_col_width:
name = name[:name_col_width-3] + "..."
print(f"{name:<{name_col_width}} | {item['type']:<4} | {get_size_format(item['size']):>10} | {draw_bar(percent)} {percent:.1f}%")
# Print Top N Largest Files
print("\n" + "=" * 70)
print(f"TOP {top_n} LARGEST FILES IN TREE")
print("-" * 70)
for i, (fpath, fsize) in enumerate(all_files_flat[:top_n]):
# readable path relative to scanned dir
rel_path = fpath.replace(abs_path, "")
if len(rel_path) > 50:
rel_path = "..." + rel_path[-47:]
print(f"{i+1:<2}. {get_size_format(fsize):>10} : {rel_path}")
# --- Entry Point ---
def main():
parser = argparse.ArgumentParser(description="Python Disk Usage Analyzer")
parser.add_argument("path", nargs="?", default=".", help="The path to analyze (default: current dir)")
parser.add_argument("-n", "--number", type=int, default=10, help="Number of top large files to show")
args = parser.parse_args()
try:
analyze_disk(args.path, args.number)
except KeyboardInterrupt:
print("\nOperation cancelled by user.")
sys.exit(0)
if __name__ == "__main__":
main()
How to use it
-
Save the file: Save the code above as pydu.py.
-
Make it executable (Optional, Linux/Mac):
chmod +x pydu.py
-
Run it:
Scan the current directory:
python3 pydu.py
Scan a specific path:
python3 pydu.py /var/log
Scan specific path and show top 20 files:
python3 pydu.py C:\Users\Start\Downloads -n 20
How it works (Code Analysis)
os.scandir: I used os.scandir instead of os.walk where possible. scandir returns an iterator of DirEntry objects which contain file attribute information (like size) cached from the operating system directory listing. This is significantly faster than calling os.stat() manually on every file.
- Recursion (
get_directory_stats): This function dives deep into folders. It sums up the size of the folder and accumulates a list of every single file found (path and size) so we can calculate the "Top Largest Files" later.
- Permission Handling: The usage of
try...except blocks around OS calls prevents the script from crashing if it encounters a system folder (like Windows System Volume Information or Linux /proc) that the user doesn't have permission to read.
- Visuals:
get_size_format: Uses standard math to convert raw bytes into KB/MB/GB.
draw_bar: Creates a simple text-based bar chart ([████------]) to visualize how much space a subfolder takes relative to the total scanned directory.
- ANSI Escape Codes: Used
\033[1;32m to make the Total Size green in the terminal.
Recommended Enhancement
If you want to make this tool look prettier (colors, tables, progress bars) and don't mind installing a library, you can install Rich:
pip install rich
Replacing the print statements with rich.console.Console and rich.table.Table would make the output look like a professional modern CLI tool (similar to ncdu).