Building a Disk Analysis and Cleanup Tool Fast with LLMs: A Practical Guide
This article walks through using large language models to quickly build a safe disk space analysis and cleanup tool. It covers how to write structured prompts that produce usable first-draft code, how to review and test generated code, a working Python implementation for scanning large files and planning deletions, security design for cleanup logic, and practical advice on handling slow or unstable LLM services and choosing between local and cloud-based model deployment. Readers will learn a workflow that shortens the path from idea to working prototype while keeping file-system operations safe.
1. The Problem: Why Disk Space Grows Out of Control
Disk usage on personal computers and development machines rarely grows all at once. It accumulates gradually from multiple sources: dependency caches, container images, virtual environments, build artifacts, download folders, and log files all quietly consume space. By the time the system warns that the disk is nearly full, it is often hard to tell which files can be safely deleted.
The common manual approach is to open a graphical disk analyzer or run statistics commands layer by layer in a terminal. This works for experienced users, but it requires repeatedly interpreting what each path means, is inefficient, and risks accidental deletion. A small tool that combines scanning, categorization, and safe cleanup can significantly reduce the cost of this work.
Writing such a tool used to mean deciding on a scanning strategy, handling cross-platform file attributes, and designing a confirmation mechanism before any deletion. With LLMs, developers can break the requirements into clearer descriptions, have the model produce an initial implementation, and then review and revise it themselves. The value of this approach is shortening the time from idea to runnable prototype — not eliminating code review.
2. Describing Requirements in Natural Language
Prompt quality directly determines how usable the generated code is. A vague request like “write a script to clean up disk space” tends to produce generic results that lack safety guardrails. Effective descriptions usually include four elements:
- Input and scope: which root directory to scan, and whether system directories should be skipped.
- Output format: a list sorted by file size, or a report aggregated by directory.
- Constraints: for example, no permanent deletion; preview only by default.
- Runtime environment: operating system type and language version.
Here is a structured requirement description you can use as a prompt template:
Goal: Scan a given root directory and identify the largest files and directories.Input: root directory path, minimum file size threshold, maximum number of results to return.Output: a list sorted by size in descending order, containing the path and a human-readable size string.Constraints:1. Do not follow symbolic links, to avoid double counting or out-of-scope access.2. Skip and log permission errors instead of aborting the whole scan.3. The cleanup feature prints a plan only by default; deletion requires an explicit flag.Environment: Python 3, standard library only.
The more specific the description, the more likely the model will produce a structure that matches your expectations. Keep in mind that generated code can still miss edge cases, so validation is necessary.
3. How to Evaluate Generated Code
Review model output step by step before running it:
- Static review: check that each function has a single responsibility, exceptions are caught, and resources are properly released.
- Small-scale verification: create files of known sizes in a temporary directory and confirm the statistics match expectations.
- Edge-case testing: cover empty directories, symbolic links, directories without permissions, and paths containing spaces or non-ASCII characters.
- Deletion logic audit: verify that the path validation before deletion is reliable and that files outside the intended directories cannot be deleted by mistake.
The fourth item matters most. Inaccurate statistics only lead to wrong results; incorrect deletions cause data loss. For any code that modifies the file system, adopt a “preview first, execute second” workflow by default.
4. Implementing the Scanning Module
The core of scanning is traversing the directory tree and reading file metadata. Three things deserve attention: don’t follow symbolic links, to avoid loops or double counting; use lstat instead of stat so file types are judged accurately; and handle per-file exceptions locally so one failure doesn’t abort the scan.
Here is an example that finds large files:
import osimport statdef find_large_files(root, min_size=100 * 1024 * 1024, limit=50):"""Return regular files under root with size >= min_size, sorted by size descending."""results = []for dirpath, _, filenames in os.walk(root, onerror=None):for name in filenames:path = os.path.join(dirpath, name)try:st = os.lstat(path)except OSError:continueif stat.S_ISREG(st.st_mode) and st.st_size >= min_size:results.append((st.st_size, path))results.sort(reverse=True)return results[:limit]def human_readable(size_bytes):"""Convert a byte count into a human-readable string."""for unit in ("B", "KB", "MB", "GB", "TB"):if size_bytes < 1024:return f"{size_bytes:.1f} {unit}"size_bytes /= 1024return f"{size_bytes:.1f} PB"
In this code, os.walk does not descend into directories pointed to by symbolic links, because the followlinks parameter defaults to False. Since lstat returns information about the link itself, symbolic links are not miscounted as regular files.
If you need usage aggregated by directory, the common approach is to accumulate each file’s size into all of its ancestor directories during traversal. This becomes expensive when file counts are large, so consider aggregating only to the first or second directory level to control memory usage and runtime.
5. Safe Design for the Cleanup Module
The main risk in cleanup comes from incorrect path validation. LLM-generated code may compare path prefixes too loosely — for example, using a simple string prefix to decide whether a file is inside a directory, which would make /data wrongly match /data2. Paths should be normalized before comparison, and prefix checks should include a separator.
The following example separates previewing from execution:
import osdef is_under_roots(path, roots):"""Check whether the normalized path is under any of the allowed root directories."""real = os.path.realpath(path)for root in roots:root_real = os.path.realpath(root)if real == root_real or real.startswith(root_real + os.sep):return Truereturn Falsedef plan_cleanup(candidates, allowed_roots):"""Filter candidate files, keeping only paths within the allowed roots."""return [p for p in candidates if is_under_roots(p, allowed_roots)]def execute_cleanup(plan, dry_run=True):"""Print the plan only by default. Files are deleted only when dry_run is False."""removed, failed = [], []for path in plan:if dry_run:print(f"[preview] {path}")continuetry:os.remove(path)removed.append(path)except OSError as exc:failed.append((path, str(exc)))return removed, failed
This design includes three layers of protection. The first is a whitelist: only files under the specified root directories can be deleted. The second is normalized path comparison, which prevents symbolic links or relative paths from bypassing the check. The third is preview by default: the caller must explicitly disable dry_run before any deletion happens.
In a production tool, you can go further by moving files to the system trash instead of deleting them directly. This capability is typically provided by the operating system or desktop environment and gives users a window to recover files. For cache files, direct deletion carries little risk; for documents, code, and database files, always keep a confirmation step.
6. The Impact of Inference Speed and Service Stability
When developing with LLM assistance, generation speed and service stability directly affect your workflow. At a typical output rate of dozens of tokens per second, a script of a few hundred lines may take tens of seconds to several minutes to generate completely. If the service times out or disconnects midway, the generated content may be incomplete and need to be requested again.
This problem is more pronounced with long contexts and multi-turn revision. Each revision may carry a large amount of history, increasing both input and output time. Developers should therefore split requirements into small, independent tasks — generate the scanning module first, then the cleanup module separately — and validate each one on its own.
When calling remote APIs, implement timeouts and retry logic on the client side. The following example shows retry logic with exponential backoff:
import timedef call_with_retry(func, retries=3, base_delay=1.0):"""Retry a call that may time out, using exponential backoff."""for attempt in range(retries):try:return func()except TimeoutError:if attempt == retries - 1:raisetime.sleep(base_delay * (2 ** attempt))
Retries only handle brief network glitches; they cannot solve prolonged service outages. A more robust approach is to keep a manual fallback path for critical workflows — for example, saving prompts and intermediate results to local files so work can resume once the service recovers.
7. Local Deployment vs. Cloud APIs
Choosing between local deployment and cloud APIs means weighing privacy, cost, performance, and maintenance effort.
Local deployment keeps data on the device, makes development immune to network fluctuations, and has low marginal cost for long-term use. The downsides are higher hardware requirements, self-managed model updates and operations, and noticeably slower inference when GPU memory or RAM is insufficient.
Cloud APIs require no hardware maintenance and usually offer higher concurrency and newer model versions. The downsides are network dependency, costs that grow with usage, and the fact that code snippets and path information pass through a third-party service — something to evaluate carefully when sensitive data is involved.
A middle ground is to choose per task: tasks involving sensitive paths or internal code run locally, while generic scripts and sample code use cloud services. Whichever route you take, avoid including credentials, account details, or personal information in your prompts.
8. Practical Recommendations
Based on this experience of building disk tools with LLMs, a few lessons stand out:
- Write the requirements first, then the code. Structured requirement descriptions reduce rework.
- Develop the statistics feature and the cleanup feature separately, and review the cleanup code on its own.
- Preview by default; delete only after explicit confirmation, and log every deleted path with a timestamp.
- Set timeouts and retries for all external calls, and keep intermediate results so you can resume from a breakpoint.
- Build test data in temporary directories to verify that the statistics and deletion scope match expectations.
Models can speed up the journey from idea to prototype, but responsibility for file system modifications still rests with the developer. Building review, testing, and safety constraints into the process is what makes a generated tool both efficient and free of data risk.
