Building a Disk Space Cleanup Script Efficiently with an AI Coding Assistant
When disk space runs low, engineers often waste time manually hunting down large files. This article walks through building a disk analysis and cleanup script with the help of an AI coding assistant, covering requirement breakdown, safe scanning and deletion logic, and practical prompt engineering tips. It includes working Python code examples and explains how to turn a one-off script into a reusable team asset.
Building a Disk Space Cleanup Script Efficiently with an AI Coding Assistant
Background: When the Disk Alert Hits
For engineers who develop in local environments, running out of disk space is a recurring classic problem. Package caches, log files, container images, build artifacts, dataset copies — these files quietly accumulate until one day the system throws a “disk full” warning, builds fail, services can’t write logs, and processes get killed by the OS.
The traditional approach is to manually run built-in disk inspection commands, walking through directories, sorting by size, and deciding from experience what can be deleted. This works, but it has three obvious pain points:
- Time-consuming and repetitive: You retype the same command combinations every time, with nothing carried over.
- Risk of accidental deletion: Deleting files on intuition is risky, especially when caches and temp files of running processes are easy to confuse.
- No visualization: Plain text output makes it hard to quickly locate where the big files are concentrated.
If your team doesn’t have an existing ops toolchain, writing a small disk analysis and cleanup tool yourself is actually the most flexible option. And today, with an AI coding assistant, the cost of developing such “one-off scripts” has dropped dramatically: a clear requirement description often produces a usable first version of the code.
Requirement Breakdown: Turning a Vague Idea into an Executable Spec
Before describing your requirements to an AI coding assistant, doing a requirement breakdown yourself significantly improves the quality of the generated code. A competent disk analysis and cleanup tool should at least include:
- Scan and statistics: Recursively traverse a target directory, sum up the sizes of subdirectories and files, and support sorting by size in descending order;
- Threshold filtering: Only show entries above a size threshold, so output isn’t drowned by海量 tiny files;
- Type categorization: Identify common cleanable file types, such as logs, archives, temp files, and build caches;
- Safe cleanup: Support a “preview mode” (list what would be deleted without actually deleting), and only execute deletion after confirmation;
- Report output: Generate a clear analysis report for archiving or sharing.
In one sentence: scan the disk, find the largest directories and files, categorize what can be safely cleaned, preview, then delete after confirmation.
This sentence works both as a development guideline and as the skeleton of a prompt for an AI coding assistant. Experience shows that the more specific the constraints in the prompt — for example, explicitly stating “preview first, delete later,” “skip files currently in use,” and “output human-readable size units” — the closer the generated code is to a runnable state.
Core Implementation: Key Design Points of the Analysis Module
The core of disk analysis is a directory traversal plus size aggregation. A sketch implementation:
import osfrom collections import defaultdictdef scan_directory(root, min_size_mb=100):stats = defaultdict(int)large_files = []threshold = min_size_mb * 1024 * 1024for dirpath, dirnames, filenames in os.walk(root):# Skip symlinked directories to avoid circular traversaldirnames[:] = [d for d in dirnamesif not os.path.islink(os.path.join(dirpath, d))]for name in filenames:path = os.path.join(dirpath, name)try:size = os.path.getsize(path)except OSError:continue # No permission or file already gonestats[dirpath] += sizeif size >= threshold:large_files.append((path, size))return stats, sorted(large_files, key=lambda x: -x[1])
Several engineering details in this code are worth noting:
- Exception tolerance: When traversal hits permission errors or files deleted concurrently, skip instead of crash — this is key to the script finishing in a real environment;
- Symlink handling: Don’t follow symlinks to prevent directory loops;
- Human-friendly size units: When displaying, convert bytes to GB/MB to improve report readability.
Once the analysis module is done, you can also aggregate into a “top-level directory view”: compute the total footprint of each top-level directory so users can see at a glance where the space is going. This aggregation is essentially rolling up leaf directory sizes level by level — simple to implement, but extremely helpful for decision-making.
The Cleanup Module: Safety Is Always the Top Priority
Cleanup looks simple but carries the highest risk. A responsible cleanup script should have multiple built-in safeguards:
- Preview first: Default to dry-run mode, printing only the “planned deletion” list and estimated freed space; actual deletion requires an explicit confirmation flag;
- Blacklist and whitelist: The blacklist lists forbidden paths (e.g., system directories, user document directories); the whitelist restricts cleanup to specific file types (e.g., logs untouched for N days, build artifact directories);
- Time-based checks: When deleting log-type files, use “last access time older than a threshold” as the condition to avoid deleting files being actively written;
- Deletion audit trail: Log every deleted file so problems can be traced later.
Sketch code:
import timedef clean_files(candidates, dry_run=True, min_age_days=30):now = time.time()freed = 0for path in candidates:try:age_days = (now - os.path.getatime(path)) / 86400if age_days < min_age_days:continuesize = os.path.getsize(path)if dry_run:print(f"[Preview] Would delete {path} ({size / 2**20:.1f} MB)")else:os.remove(path)print(f"[Deleted] {path}")freed += sizeexcept OSError as e:print(f"[Skipped] {path}: {e}")return freed
These safety strategies are exactly what AI coding assistants tend to “miss” — without explicit requirements in the prompt, the generated result often calls the delete function directly. Explicitly stating in the prompt “must support preview mode, must skip recently accessed files” is a key technique for getting usable output.
Prompt Engineering: A Methodology for Generating High-Quality Scripts in One Pass
From this exercise, a few general lessons emerge for working with AI coding assistants:
- Give the scenario first, then the features: “My disk is full and I need a script to find large files and safely clean them up” helps the model understand intent better than a bare feature list;
- Specify the tech stack and runtime environment: Specify the scripting language, target OS, and whether third-party dependencies are allowed, to avoid generating code that can’t run;
- Write safety constraints as hard requirements: Preview mode, path blacklists, confirmation interactions — these must be explicitly requested;
- Iterate: After getting the skeleton in the first round, refine report format, concurrent scanning, interactive confirmation, and other details in subsequent rounds — this works better than one giant prompt.
Worth noting: different coding assistants differ noticeably in “thinking length.” Some assistants run lengthy internal reasoning before generating output, and for lightweight tasks like “write a script,” the wait cost outweighs the benefit. For simple, well-defined script requests, a fast, direct assistant gives a better experience; for complex architecture design, moderately deeper reasoning pays off. Developers should choose flexibly based on task complexity.
Going Further: From Personal Script to Platform Capability
Once such a tool spreads within a team, consider platform-level evolution: write scan results to a logging service for long-term trend analysis, and pair with monitoring alerts to automatically trigger cleanup when disk usage hits a threshold. In cloud scenarios, you can combine object storage lifecycle policies to automatically tier cold data or expire it, reducing space pressure at the source.
Conclusion
A disk cleanup script is small, but it’s an excellent sample for observing “how AI coding assistants change the way we develop”: the clearer the requirement description, the more reliable the output; safety constraints must be proactively declared; and the value of the tool lies not in the code itself but in turning repetitive labor into reusable assets. Master this approach, and similar ops utilities can go from idea to working tool in minutes.
