Efficient Coding with LLMs and a Practical Disk Cleanup Strategy
This article explains how to use an efficient coding model to build a cross-platform disk space analysis and cleanup helper. It covers the traits that make a coding model practical for engineering work, how to write a one-line prompt that includes safety constraints, a reference four-layer code structure, mandatory safety rules for cleanup tools, performance tuning for large file sets, and a path from local scripts to cloud-based capacity governance. Readers will get a reusable prompt template, sample Python code, and a checklist for turning a one-off cleanup into a repeatable process.
1. Background: The Real Engineering Challenge Behind a Full Disk
A developer’s local disk filling up is a frequent but often underestimated problem. It is rarely caused by a single oversized file. More often, it is the long-term accumulation of build caches, dependency packages, logs, container image layers, model weights, and temporary export files. When available space approaches a critical level, compilation failures, database write errors, logs that cannot be flushed to disk, and interrupted system updates start to appear one after another. Diagnosing these issues costs far more than the cleanup itself.
The traditional approach is manual: enter directories one level at a time, sort by size, and decide what to delete based on experience. This has two clear drawbacks. First, the judgment depends on individual experience, so intermediate artifacts that are still referenced may be deleted by mistake. Second, it is not reusable; switching to another machine means starting over. Handing this kind of task—clear rules, controllable risk, and a certain amount of code—to a model with efficient coding ability is a suitable entry point.
2. What Makes a Coding Model Practical: From “Can Write” to “Easy to Use”
In real use, a coding model that fits engineering work usually has the following traits. These traits matter more to the experience than a leaderboard score alone:
- Controllable reasoning pace: For medium-complexity tasks, it does not get stuck in lengthy internal deliberation and reaches code output quickly, reducing waiting time.
- High first-pass completeness: It proactively fills in the key constraints of a request (read-only by default, configurable thresholds, report output) instead of returning a partial script.
- Clear structure: It tends to output modular code, separating “scan,” “aggregate,” “decide,” and “execute,” which makes manual review easier.
- Caution with dangerous operations: It does not delete by default but first produces a candidate list, in line with engineering safety practice.
It is worth stressing that model capability is only one variable. Prompt quality and safety boundary design are equally important.
3. Prompt Design: What a One-Line Request Must Contain
A “one-line prompt” does not mean a vague description. A high-quality one-liner usually implies the goal, the constraints, and the delivery format. The following template is a useful reference:
Write a cross-platform disk space analysis and cleanup helper:1) Read-only scanning by default; do not delete any file;2) Support filtering by directory depth and file size threshold;3) Output a Top N report sorted by space usage;4) Deletion must be explicitly enabled and support a dry run;5) Use the standard library only, with usage instructions.
The two most important lines are “read-only by default” and “explicitly enabled deletion.” These constraints keep irreversible risk outside the code and give later manual review something concrete to rely on.
4. A Reference Structure for the Generated Code
A sound implementation is usually split into four layers: a traversal layer that collects metadata, an aggregation layer that groups by directory, a decision layer that filters by rules, and an execution layer that outputs or performs controlled deletion. Sample code:
import osfrom collections import defaultdictdef scan(root, top_n=20):stats = defaultdict(int)for dirpath, _, filenames in os.walk(root):for name in filenames:path = os.path.join(dirpath, name)try:stats[dirpath] += os.path.getsize(path)except OSError:continue # skip permission errors or broken linksranked = sorted(stats.items(), key=lambda x: x[1], reverse=True)return ranked[:top_n]def human(size):for unit in ("B", "KB", "MB", "GB", "TB"):if size < 1024:return f"{size:.1f}{unit}"size /= 1024return f"{size:.1f}PB"if __name__ == "__main__":for path, size in scan(".", 15):print(f"{human(size):>10} {path}")
This code is deliberately restrained: no recursive deletion, no following symbolic links, no swallowing permission errors. That makes it easy to layer whitelists and logging on top.
5. Safety Boundaries: Red Lines Every Cleanup Tool Must Follow
Cleanup tools carry higher risk than ordinary scripts, so these rules should be fixed as engineering standards:
- Dry run by default: First output the list of “to be deleted” items and the total space to be freed; execute only after manual confirmation.
- Whitelist first: System directories, version control directories, and sync drive directories are excluded by default.
- Age threshold: Only handle caches and temporary files not accessed for more than N days.
- Keep an audit trail: Record the deleted path, time, and size for traceability.
- Batch execution: Set an upper limit on space freed per run to avoid I/O jitter caused by a sudden burst of deletions.
6. Performance and Experience Tuning
When the scan scope reaches millions of files, the bottleneck is usually metadata reads rather than computation. Options include an incremental cache that records the previous traversal result, a maximum depth limit, parallel directory traversal, and scanning known large-usage directories first. Results should also be written as a structured report and paired with monitoring alerts that notify in advance when available space drops below a threshold, shifting from “cleanup after the fact” to “early warning.”
7. From a Local Script to Cloud Governance
If a single-machine script can no longer meet the need for consistent governance across multiple machines and environments, the same idea can be moved to a combination of general cloud capabilities: object storage to archive cold data centrally, a log service to collect cleanup audit records, monitoring alerts to set thresholds on capacity levels, and a container platform to schedule periodic tasks uniformly. Baidu AI Cloud offers corresponding capabilities in these general cloud product categories, which can be combined as needed into a closed loop of “collect—decide—execute—audit.”
8. Real Constraints on the Model Call Path
Another common pain point in practice is unstable call throughput: the same model performs noticeably differently across access methods, and long-context requests are more prone to interruption. Practical mitigations include splitting large tasks into smaller requests, caching generated results locally, implementing retry and timeout backoff on the client, and deploying stable inference capability closer to the data. Local deployment is especially valuable for data-sensitive scenarios, improving both latency and compliance at the same time.
9. Conclusion
Generating a disk cleanup tool from a one-line prompt works because the task boundary is clear and verification cost is low. What really decides success is not whether the model can write the code, but whether we have written the safety constraints into the requirements. Fixing read-only by default, explicit deletion, and audit trails as standard practice, then combining an efficient coding model with general cloud capabilities, turns a one-off firefighting action into a sustainable capacity governance mechanism.
