Complete Guide to Writing Disk Cleanup Scripts with Lightweight Code Models

    This article explores how to use lightweight code models to generate disk cleanup scripts. It covers the advantages and limitations of lightweight models for scripting tasks, provides a step-by-step guide to generating and refining a disk space analysis script using a single prompt, and details a safe cleanup process involving dry runs, file quarantine, and logging for recoverability.

    1. What Tasks Suit Lightweight Code Models

    In LLM applications, not every task requires the largest parameters or longest reasoning chains. Daily development involves many script needs with “clear patterns and well-defined boundaries,” such as log rotation, batch renaming, and disk usage analysis. These tasks share short context, few dependencies, and quick verification.

    Lightweight code models are perfect for this, offering three main advantages. First, low response latency; the time from sending a request to receiving the first token is short, maintaining a continuous thought flow. Second, concise output; the model prefers giving executable code directly rather than lengthy analysis. Third, low resource consumption; whether billed by tokens or deployed locally, costs are easy to control.

    They also have clear boundaries. If a task involves multi-file dependencies, long contexts, or complex concurrency, output reliability drops. The task should be split into smaller steps. In clear boundary scenarios, you can quickly get a modifiable draft and adjust it through a few rounds of dialogue.

    Note that model-generated code isn’t inherently correct. Drafts may have statistical omissions, missing exception handling, or even truncation mid-code. Therefore, the model draft must undergo human review and run in a test environment before being used for production directory cleanup.

    2. How to Generate a Scanning Script with a Single Prompt

    Assume a workstation’s large disk is almost full, and you need to find the directories consuming the most space. You can write a prompt like this:

    Please write a disk space analysis tool in Python with the following requirements: recursively scan a specified directory, sort by subtree disk usage, and output the Top 20; use lstat without following symbolic links; log and skip directories without permission.

    “Subtree usage” refers to the size of the directory’s own files plus all subdirectories. Parent directories contain subdirectories, so parents usually rank higher. Pay attention to this nesting; otherwise, it’s easy to double-count the same files across levels.

    Path Direct File Size Subtree Usage
    /data 0 GB 10 GB
    /data/cache 2 GB 6 GB
    /data/cache/logs 4 GB 4 GB

    In the table above, the 4 GB of /data/cache/logs is also counted in /data/cache and /data subtree usage. Having both parent and child in the Top 20 is normal and doesn’t mean duplicate disk usage.

    Model drafts often only count direct files without accumulating subdirectories, skewing the ranking. The following code accumulates bottom-up, fixing this issue.

    1. import logging
    2. import os
    3. import stat
    4. logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
    5. log = logging.getLogger("scan")
    6. def on_error(err: OSError) -> None:
    7. log.warning("Cannot access directory %s: %s, skipped", err.filename, err.strerror)
    8. def subtree_sizes(root: str) -> dict[str, int]:
    9. """Returns the subtree usage in bytes for each directory (own files plus all subdirectories)."""
    10. root = os.path.abspath(root)
    11. sizes: dict[str, int] = {}
    12. # topdown=False processes child directories before parent directories, so the parent can directly get the child's result
    13. # followlinks remains the default False, symlink directories only appear in dirnames and will not be traversed
    14. for dirpath, dirnames, filenames in os.walk(root, topdown=False, onerror=on_error):
    15. total = 0
    16. for name in filenames:
    17. full = os.path.join(dirpath, name)
    18. try:
    19. st = os.lstat(full) # lstat does not follow symbolic links
    20. except OSError as e:
    21. log.warning("Cannot read %s: %s, skipped", full, e)
    22. continue
    23. if stat.S_ISREG(st.st_mode):
    24. total += st.st_size
    25. for name in dirnames:
    26. # Symlink directories are not in sizes, so it gets 0 here
    27. total += sizes.get(os.path.join(dirpath, name), 0)
    28. sizes[dirpath] = total
    29. return sizes
    30. def top_n(root: str, n: int = 20) -> None:
    31. sizes = subtree_sizes(root)
    32. ranked = sorted(sizes.items(), key=lambda kv: kv[1], reverse=True)[:n]
    33. for path, size in ranked:
    34. print(f"{size / 1024**3:.2f} GB\t{path}")
    35. if __name__ == "__main__":
    36. top_n("/data")

    This code requires Python 3.9 or higher because it uses type hints like dict[str, int].

    The statistical boundaries of this code need clarification.

    First, lstat is only used for files. For symlink files, lstat returns the link’s own size, not the target’s. stat.S_ISREG excludes symlinks, so linked files aren’t counted.

    Second, directory symlinks rely on os.walk‘s default behavior. When followlinks is False, os.walk won’t enter symlinked directories, so data elsewhere won’t be counted. The subdirectory size retrieved is 0, which is correct.

    Third, hard links are double-counted. If the same inode appears twice in the directory tree, the code adds its size twice. If there are many hard links, the statistics will be inflated.

    Fourth, permission errors must be logged. os.walk calls on_error for unreadable directories, and individual file lstat failures go to the except branch. Both log and continue scanning without interrupting the task.

    Common errors in model drafts can be categorized into four types: only counting direct files, following symlinks, lacking a path whitelist, and silently ignoring permission errors. Check these four points when reviewing the code.

    3. Screening and Confirmation: Screen First, Confirm Next, Move Last

    Scanning only tells you what’s taking up space, not what can be deleted. The cleanup phase aims to screen candidate files, list them, and only act after human confirmation. The code below defaults to a dry run, modifying no files. After confirmation, files are moved to a quarantine directory instead of being directly deleted.

    Before acting, check the following:

    1. Run test scripts in a test environment completely separate from production.
    2. Make a full backup of the directory to be cleaned and verify restorability.
    3. Ensure ALLOWED_ROOTS only contains directories allowed for cleanup, excluding home, root, or database directories.
    4. Ensure the quarantine directory is not in the same hierarchy as the cleaned directory to avoid re-scanning.
    5. Perform a dry run first, review the output list item by item, then decide whether to add --apply.
    1. import argparse
    2. import logging
    3. import os
    4. import shutil
    5. import stat
    6. import time
    7. from datetime import datetime
    8. from pathlib import Path
    9. ALLOWED_ROOTS = [Path("/data/cache").resolve()] # Whitelist: only these directory trees are allowed to be processed
    10. DENY_PATHS = {Path("/").resolve(), Path.home().resolve()} # Hardcoded denied sensitive paths
    11. QUARANTINE = Path("/data/quarantine").resolve() # Quarantine directory, must be outside the cleaned directory
    12. LOG_FILE = "cleanup.log"
    13. def setup_logging() -> logging.Logger:
    14. logger = logging.getLogger("cleanup")
    15. logger.setLevel(logging.INFO)
    16. fmt = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
    17. file_handler = logging.FileHandler(LOG_FILE, encoding="utf-8")
    18. file_handler.setFormatter(fmt)
    19. console = logging.StreamHandler()
    20. console.setFormatter(fmt)
    21. logger.addHandler(file_handler)
    22. logger.addHandler(console)
    23. return logger
    24. log = setup_logging()
    25. def check_root(root: Path) -> Path:
    26. root = root.resolve()
    27. if root in DENY_PATHS:
    28. raise SystemExit(f"Denied operating on sensitive directory: {root}")
    29. if not any(root == a or a in root.parents for a in ALLOWED_ROOTS):
    30. raise SystemExit(f"Directory not in whitelist: {root}")
    31. if root == QUARANTINE or root in QUARANTINE.parents:
    32. raise SystemExit(f"Cleaned directory contains quarantine directory, risk of re-scanning: {root}")
    33. return root
    34. def on_walk_error(err: OSError) -> None:
    35. log.warning("Cannot access directory %s: %s, skipped", err.filename, err.strerror)
    36. def find_candidates(root: Path, days: int) -> list[Path]:
    37. """Returns regular files modified earlier than 'days' days ago. Symlinks and directories will not be in the result."""
    38. cutoff = time.time() - days * 86400
    39. result: list[Path] = []
    40. for dirpath, _dirnames, filenames in os.walk(root, onerror=on_walk_error):
    41. for name in filenames:
    42. path = Path(dirpath) / name
    43. try:
    44. st = os.lstat(path)
    45. except OSError as e:
    46. log.warning("Cannot read %s: %s, skipped", path, e)
    47. continue
    48. if stat.S_ISREG(st.st_mode) and st.st_mtime < cutoff:
    49. result.append(path)
    50. return result
    51. def safe_size(path: Path) -> int:
    52. try:
    53. return os.lstat(path).st_size
    54. except OSError:
    55. return 0
    56. def target_path(src: Path, root: Path, batch: str) -> Path:
    57. """Maintains relative path structure, placing into this batch's quarantine directory."""
    58. return QUARANTINE / batch / src.relative_to(root)
    59. def move_files(files: list[Path], root: Path, batch: str, dry_run: bool) -> None:
    60. for src in files:
    61. dst = target_path(src, root, batch)
    62. size = safe_size(src)
    63. if dry_run:
    64. log.info("[DRY-RUN] Will move %s -> %s (%d bytes)", src, dst, size)
    65. continue
    66. try:
    67. dst.parent.mkdir(parents=True, exist_ok=True)
    68. shutil.move(str(src), str(dst))
    69. log.info("MOVED %s -> %s (%d bytes)", src, dst, size)
    70. except OSError as e:
    71. log.error("FAILED %s -> %s: %s", src, dst, e)
    72. def confirm(count: int, total: int) -> bool:
    73. print(f"Files about to be moved to quarantine: {count}, approx {total / 1024**2:.1f} MB")
    74. return input("Type YES to confirm execution, other input cancels: ").strip() == "YES"
    75. def main() -> None:
    76. parser = argparse.ArgumentParser(description="Move old files to quarantine directory based on modification time (dry run by default)")
    77. parser.add_argument("root", help="Directory to clean, must be in the whitelist")
    78. parser.add_argument("--days", type=int, default=30, help="Files modified earlier than how many days ago are candidates")
    79. parser.add_argument("--apply", action="store_true", help="Actually move files after confirmation")
    80. args = parser.parse_args()
    81. root = check_root(Path(args.root))
    82. batch = datetime.now().strftime("%Y%m%d-%H%M%S")
    83. files = find_candidates(root, args.days)
    84. if not files:
    85. log.info("No matching candidate files: %s", root)
    86. return
    87. total = sum(safe_size(f) for f in files)
    88. log.info("Scan complete: %s, %d candidates, approx %d bytes", root, len(files), total)
    89. if not args.apply:
    90. move_files(files, root, batch, dry_run=True)
    91. log.info("Dry run finished, no files modified. Review list then execute with --apply.")
    92. return
    93. if not confirm(len(files), total):
    94. log.info("User cancelled, no files moved")
    95. return
    96. move_files(files, root, batch, dry_run=False)
    97. log.info("Batch %s complete, quarantine directory: %s", batch, QUARANTINE / batch)
    98. if __name__ == "__main__":
    99. main()

    The execution order is: check paths, screen candidates, output list. By default, it only does a dry run. With --apply, the script totals the size and requires inputting YES. It only moves files upon explicit confirmation. Other inputs or running in a non-interactive environment cancels the operation.

    Whitelist and sensitive path checks are placed first. If any fail, the script exits without even scanning. Candidate files only come from within whitelisted directories, and symlinks and directories aren’t included, so the script won’t mistakenly alter system files due to a link pointing to /etc.

    4. Quarantine and Logging: Recovery is Safer than Direct Deletion

    The core of this process is “move to quarantine” rather than direct deletion. Files are moved to /data/quarantine/<batch_time>/ while preserving their original relative paths. For example, /data/cache/old/big.bin moves to /data/quarantine/20261125-053000/old/big.bin. This has two benefits: misjudgments can be restored as-is, and quarantine contents can be traced by batch.

    The retention period for the quarantine directory is up to the team. For 14 days, you can list expired batches first and manually review before cleaning:

    1. find /data/quarantine -mindepth 1 -maxdepth 1 -mtime +14 -print

    This only prints results without deleting. After verifying the list, delete manually.

    To restore a file, ensure the original directory exists, then move it back:

    1. mkdir -p /data/cache/old
    2. mv /data/quarantine/20261125-053000/old/big.bin /data/cache/old/

    The log file cleanup.log outputs to both file and console. Each record includes time, level, and action. [DRY-RUN] indicates a dry run plan, MOVED indicates a completed move with path and bytes. FAILED indicates a failed move, usually due to insufficient permissions or disk space. WARNING indicates skipped directories or files. When reviewing, search logs by batch time to see all files and sizes involved.

    5. Test Verification: Run in Test Environment First, Then Production

    The test environment should be isolated from production. The following steps use a temporary directory and won’t touch real data.

    Step 1: Modify the script constants to point to test directories:

    1. ALLOWED_ROOTS = [Path("/tmp/test_cache").resolve()]
    2. QUARANTINE = Path("/tmp/test_quarantine").resolve()

    Step 2: Construct test data. The following commands create a 50 MB old file, a new file, and a symlink pointing to /etc:

    1. mkdir -p /tmp/test_cache/old /tmp/test_cache/recent
    2. head -c 50M /dev/zero > /tmp/test_cache/old/big.bin
    3. touch -d "60 days ago" /tmp/test_cache/old/big.bin
    4. echo "new" > /tmp/test_cache/recent/new.txt
    5. ln -s /etc /tmp/test_cache/recent/etc_link