basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    What’s taking up disk space: the biggest files in one script

    The script walks a folder with everything inside, collects file sizes into a list, sorts it and prints the 15 biggest with their size in KB, MB, GB. A Windows home folder — 79 thousand files, 16 GB — takes 15 seconds. The script deletes nothing; it only shows.

    What you end up with

    The output for the folder Python itself lives in:

    2328 files, 156.4 MB in total
    The biggest 15:
       21.6 MB  DLLs\libcrypto-3-x64.pdb
       21.0 MB  python315.pdb
        7.5 MB  DLLs\libcrypto-3-x64.dll
        6.9 MB  python315.dll
        5.2 MB  DLLs\sqlite3.pdb
       …

    Step by step

    1. Write the script

      The file biggest.py:

      from pathlib import Path
      
      FOLDER = Path.home()
      TOP = 15
      
      
      def human(size):
          """Bytes into KB, MB, GB: 3_400_000_000 -> "3.2 GB"."""
          for unit in ["B", "KB", "MB", "GB"]:
              if size < 1024:
                  return f"{size:.1f} {unit}"
              size = size / 1024
          return f"{size:.1f} TB"
      
      
      files = []
      total = 0
      for path in FOLDER.rglob("*"):
          if path.is_file() and not path.is_symlink():
              size = path.stat().st_size
              files.append((size, path))
              total = total + size
      
      files = sorted(files, reverse=True)
      print(f"{len(files)} files, {human(total)} in total")
      print(f"The biggest {TOP}:")
      for size, path in files[:TOP]:
          print(f"{human(size):>10}  {path.relative_to(FOLDER)}")
    2. Run it

      python biggest.py

      A Windows home folder of 79 thousand files takes 15 seconds. Usually the first to surface are installers in Downloads, videos, and program caches in AppData — test browsers, local models.

    3. Look at another folder

      Change FOLDER: Path.home() / "Videos", or a whole data drive — Path("D:/"). A different number in the output: TOP = 30.

    What’s new here

    • A list. files = [] is an empty list, files.append(…) adds to the end, len(files) is how many it holds. Here the list holds (size, path) pairs — tuples: two values in one set of parentheses. In the loop they’re unpacked into two variables right away: for size, path in ….
    • Sorting: sorted. Returns a new list in ascending order; reverse=True makes it descending. Pairs compare by their first element, so the sort goes by size.
    • The [:n] slice. files[:15] is the first 15 items. [5:10] is the sixth through the tenth, [-3:] the last three. It works on strings too: in A 120-bit password, [:length] cut the password to the needed length.
    • An f-string. A string with f before the quotes substitutes values into {}: f"{human(total)} in total". After a colon comes the format: {size:.1f} is one digit after the point, {…:>10} right-aligns in 10 characters so the size column lines up.

    rglob("*") gives every file and folder at any depth; iterdir() in Sort Downloads saw only the top level.

    If it doesn’t work

    The script thinks for several minutes

    Cause
    The folder has millions of small files — node_modules, caches, mail archives: each file costs a disk request.
    Fix
    Narrow the folder: FOLDER = Path.home() / "Downloads". Or stop it with Ctrl+C and run it on parts.

    The “total” is less than the folder’s Properties or the disk’s used space

    Cause
    The script skips links (is_symlink) and silently walks around folders it has no permission for: rglob doesn’t open them and doesn’t crash. Properties also round each file up to a cluster.
    Fix
    For your own folders the difference is small. The home folder shows what fills the disk; system folders need administrator rights.

    How to check

    Put a file that’s clearly bigger than the rest into the folder — a copy of a video, say — and run the script: it comes first in the list, and its size matches the file’s Properties in Explorer.