Disk Space Analysis and Cleanup with LLMs: A Practical Guide
This article explains how to use AI coding models to build a disk space analysis and cleanup tool. It covers what a reusable prompt must specify, a three-layer design of measurement, reporting, and controlled deletion, handling of symlinks and hard links, permission and mount point edge cases, and a four-step validation process. The emphasis is on dry-run defaults, protected paths, and repeatable reports so that generated scripts remain safe and auditable.
1. Why Disks Fill Up “Suddenly”
A developer’s local disk rarely fills up for a single reason. It is usually several growth patterns stacking on top of each other: dependency packages and build caches expanding continuously, container images and log files piling up, local database copies and exported files, indexes and history snapshots left behind by editors and AI coding tools, and large files in the downloads directory that were forgotten long ago. Most file systems do not proactively tell you which directory is consuming space, so the problem usually surfaces only when a build fails, a database write errors out, or the system cannot create a temporary file.
Manual investigation means walking into directories one level at a time and running statistics commands repeatedly. The process is tedious and easy to miss hidden directories and mount points. Handing this kind of task—clear goal, clear rules, repetitive operations—to an AI coding model to generate a script is currently one of the more efficient approaches. The key is not whether the model can write code, but whether the developer can state the constraints clearly and review the generated result rigorously.
2. What a One-Line Prompt Must Contain
Prompts like “write me a disk cleanup program” produce unstable results because they lack verifiable boundaries. A reusable prompt template should cover at least five categories of information:
Goal: Report the usage of each first-level subdirectory under a given path, and list the top N largest filesConstraints: Read-only by default (dry-run); deletion must be explicitly enabled and confirmed twiceEnvironment: Target OS and runtime version; standard library only, no external dependenciesOutput: Structured text report plus an optional machine-readable format (e.g., JSON)Safety: Skip critical system directories, do not follow symlinks, aggregate single-file size and total reclaimable space
Writing “read-only first, explicit opt-in for deletion, skip critical paths” into the prompt significantly reduces the risk of accidental deletion. These three constraints essentially keep the decision on irreversible operations with the developer rather than with automatically generated logic.
3. Core Design: Measure First, Then Decide, Then Reclaim
A mature cleanup tool usually has three layers, decoupled from each other through clear data structures.
The first layer is traversal and measurement. When recursively totaling directory usage, you need an explicit policy for hard links and symlinks. Following symlinks can cause double counting or even out-of-bounds access, so the default is not to follow them. Hard links should be deduplicated within the same file system so that usage is not counted twice. Example code:
import osdef dir_size(path, follow_links=False):total = 0for root, dirs, files in os.walk(path, followlinks=follow_links):for name in files:fp = os.path.join(root, name)try:st = os.stat(fp, follow_symlinks=follow_links)except OSError:continue # permission denied or file vanished: skip instead of abortingtotal += st.st_sizereturn total
The second layer is sorting and presentation. Aggregate by first-level subdirectory, sort in descending order, and output three columns: path, usage, and percentage. Then list the largest individual files separately. Percentage is more useful for decisions than absolute values: 20GB means something very different when it is 40% of a partition versus 2% of it.
The third layer is controlled reclamation. Cleanup actions should be categorized rather than deleted with one blanket rule:
- Regenerable data: build artifacts, dependency caches, rotated log files. Safe to clean; the next build recreates them.
- Delete after confirmation: recycle bin contents, old installer packages, temporary exports.
- Do not touch: system directories, files currently held by running processes, database data files.
def safe_remove(target, protected_roots, dry_run=True):real = os.path.realpath(target)if any(real.startswith(p) for p in protected_roots):raise PermissionError(f"Protected path, operation refused: {real}")if dry_run:print(f"[dry-run] would delete: {real}")returnos.remove(real) if os.path.isfile(real) else shutil.rmtree(real)
4. Engineering Details That Are Easy to Miss
First, permissions and exceptions must be handled explicitly. Encountering directories you cannot read is normal during traversal. If an exception is raised outright, the whole scan aborts. The right approach is to record the skipped items and reflect them in the report, so the developer knows how much space was not accounted for.
Second, mount points need separate handling. Recursing across file systems slows things down considerably and makes the measurement basis inconsistent, so traversal should normally be limited to a single file system.
Third, the report must be reproducible. Include the scan time, target path, scan duration, and the number of skipped items, so two scans can be compared to judge whether cleanup actually took effect.
Fourth, make deletion reversible. Writing the deletion candidate list to a file and having a human review it before execution is the cheapest safety mechanism available.
5. Validation and Measuring Results
Do not run generated code directly in a production directory. A four-step validation is recommended: first, build large files and nested directories in a small temporary directory for functional verification; second, scan a real directory in read-only mode and check that the total matches what the file manager shows; third, enable deletion only for regenerable data and observe how much space is freed; finally, set up periodic scans so that the “disk level” becomes an observable metric rather than a sudden incident.
6. Model Capability Limits and Localization Trade-offs
Two points deserve an objective view. First, models differ markedly in “thinking length,” and a long reasoning chain does not equal higher output quality. For a well-scoped task like code generation, concise and direct output is often more practical. Second, cloud calls are affected by network conditions and server-side load; throughput fluctuations and dropped connections can happen. Important scripts should therefore be kept in a local version repository instead of regenerated repeatedly. For data-sensitive scenarios, consider deploying an open-source inference framework locally, or using model services from Baidu AI Cloud together with general-purpose capabilities such as container platforms and object storage to build a stable toolchain that keeps generation, review, and execution all under control.
7. Summary
Disk cleanup looks like a minor operations chore, but it is a complete loop: describe the requirement, generate code, review for safety, execute under control, and keep observing. Writing read-only defaults, path protection, and categorized reclamation into both the prompt and the code is what turns an AI coding model into a reliable productivity tool rather than a new source of risk.
