Disk Space Analysis and Cleanup Tool: Building It Quickly with LLMs
This article explains how to use large language models to generate a practical disk space analysis and cleanup tool. It covers why this task is well suited to LLM-assisted coding, how to design a complete prompt, the core implementation modules for directory traversal, human-readable sorting, interactive confirmation, and safe deletion, and how to turn a one-off script into a reusable utility. It also summarizes practical lessons for reviewing and operationalizing LLM-generated code.
1. A Real Pain Point: What to Do When a 1 TB Disk Is Full
Many developers have encountered this scenario: one day compilation suddenly fails or a container image pull breaks, and a quick check reveals the disk is full. A 1 TB disk sounds large, but in daily development, log files, build caches, dependency copies, and temporary files can quietly consume all available space like the classic boiling-frog problem.
Traditional solutions usually fall into two categories: opening the operating system’s built-in disk management tool and browsing directories layer by layer, or combining a string of commands to calculate directory sizes. The first approach is inefficient, and the second has a relatively high barrier for people who are not comfortable with command-line tools. Even after identifying what is taking up space, safely cleaning it up is another challenge.
This is an excellent use case for LLM coding capabilities. The requirements are clear, the logic is straightforward, and no complex business rules are involved. With a one-sentence prompt, an LLM can generate a basically usable disk space analysis and cleanup program. This article uses that as a starting point and breaks down the full practice.
2. Why This Task Fits LLMs Well
Before writing code, it is worth clarifying which programming tasks offer the best return when handed to an LLM. A disk cleanup tool happens to match several key characteristics.
First, the requirement boundary is clear. “Scan the disk, calculate usage for each directory, sort by size, and support deletion” is almost unambiguous, so an LLM is unlikely to misunderstand it.
Second, the technical path is mature. Directory traversal, file statistics, and sorted display are textbook-level general techniques. LLMs have seen many similar implementations in training data, so generation quality is generally reliable.
Third, verification cost is low. Run the generated program once, and you can immediately check whether the scan results are correct and whether deletion works. No complex test environment is required.
Fourth, there is no legacy baggage. This is a small greenfield tool. The model does not need to understand an existing codebase, so it can fully leverage its strength in generating complete code from scratch.
Conversely, if a task involves complex business semantics, deep historical code dependencies, or strict interface contracts, a single-sentence prompt will rarely get it right in one pass. Understanding the capability boundaries of LLMs is essential to using them where they are most effective.
3. Prompt Design: The Full Requirement Behind One Sentence
Although a one-sentence prompt can produce a working program, making it genuinely useful means the requirement description actually contains several important details. A high-quality prompt should cover at least the following elements:
- Input: Specify the path to scan, such as a root directory or a mount point, and limit the scan depth.
- Processing logic: Recursively calculate the cumulative size of each directory and identify large files and large directories.
- Output format: Sort by occupied space in descending order, use human-readable capacity units such as KB, MB, and GB, and preferably support Top N display.
- Interaction capability: Allow the user to select an entry, confirm deletion, and require a second confirmation before deleting.
- Safety constraints: Skip critical system directories and handle paths without permission gracefully instead of crashing.
Organize these elements in natural language. For example: “Write a Python disk space analysis tool that scans a specified directory, recursively calculates the size of each subdirectory, displays the top 20 in descending order, supports interactive selection and deletion of a specified directory, requires confirmation before deletion, and skips directories without permission with a message.” A prompt like this is already a qualified mini requirements document.
The rule of thumb is: the closer the prompt is to a complete request you would give a colleague, the closer the generated result will be to something directly usable.
4. Core Implementation Modules
Understanding how the tool works helps review whether the code generated by an LLM is reasonable. A typical disk analysis and cleanup tool contains four modules.
4.1 Directory Traversal and Size Calculation
The core is recursive traversal. Key points include traversing without following symbolic links to avoid infinite loops caused by link cycles, and wrapping file status retrieval in try/except to silently skip permission errors or files that have already been deleted. An illustrative example is below:
import osdef get_dir_size(path):total = 0for dirpath, dirnames, filenames in os.walk(path, followlinks=False):for name in filenames:fp = os.path.join(dirpath, name)try:total += os.path.getsize(fp)except OSError:continuereturn total
A more efficient approach is to accumulate the size of each top-level directory during a single traversal, avoiding repeated walk calls for each directory. This can make a significant performance difference when the disk contains a very large number of files.
4.2 Sorting and Human-Readable Display
After statistics are collected, sort by size in descending order, take the Top N, and convert byte counts into readable units:
def human_readable(size):for unit in ['B', 'KB', 'MB', 'GB', 'TB']:if size < 1024:return f"{size:.1f} {unit}"size /= 1024return f"{size:.1f} PB"
4.3 Interactive Selection and Second Confirmation
This is the key step that moves the tool from “analysis” to “cleanup.” After listing candidate directories, let the user enter an index. Before deletion, print the full path and require the user to enter a confirmation character. This interaction logic looks simple, but it is the core of the safety line.
4.4 Safe Deletion Strategy
Deletion is the only irreversible operation in the entire tool, so it must be protected carefully. The following principles are recommended:
- Maintain a blacklist that refuses deletion of critical system paths by default, such as system directories and the root level of a user’s home directory.
- Prefer moving items to a recycle directory instead of physically deleting them directly, leaving room to recover from mistakes.
- Before deletion, verify again that the path is still within the candidate set from the scan results, preventing path tampering.
- Keep an operation log recording what was deleted and when, so actions are traceable.
If the code generated by an LLM directly calls recursive deletion on arbitrary paths without any protection, these safeguards must be added manually. This is an essential review step when using AI-generated code.
5. From Emergency Script to Reusable Tool
After the tool works, it is worth doing a few engineering finishing steps to turn a one-off script into a long-term asset:
- Parameterization: Make the scan path, Top N count, and depth limit command-line arguments instead of hardcoding them.
- Add scan reports: Output analysis results as text or structured files for archiving and comparison.
- Add scheduling: Use the system’s scheduling capability to scan periodically, and when disk usage exceeds a threshold, notify people through general monitoring and alerting capabilities.
- Share with the team: Share small tools like this internally. It can significantly reduce the repeated cost of handling similar problems.
6. Lessons from LLM-Assisted Programming
Finally, here are some methodology lessons from this practice. First, LLMs are best at “clear-requirement, from-scratch construction tasks.” Treat the model as an on-call full-stack intern: give it a clear requirements document, and its output often exceeds expectations. Second, generation speed and user experience matter. Long reasoning waits can interrupt flow, so choosing a fast, responsive model configuration can noticeably improve the coding experience. Third, generated code must be reviewed by a human, especially when it involves high-risk operations such as file deletion, network requests, or credential handling. It is better to review one extra time. Fourth, if there are higher requirements for data privacy or invocation stability, consider deploying the model locally or in a private environment to avoid dependence on the availability of a remote interface. This is a direction more and more teams are exploring.
Disk cleanup is only a small entry point, but it demonstrates a typical paradigm for LLM-assisted development: humans define the problem and control safety, while the machine quickly generates the implementation. Once this paradigm is mastered, similar efficiency tools can be built with ease.
