liveBook · Manning

Os.path.getsize

As explained in The Quick Python Book, Fourth Edition

os.path.getsize is a Python os.path function that returns the size of the file or filesystem object at a path.

os.path.getsize(path) returns the size of the file or filesystem object identified by a pathname. section 12.3

Use it when traversing files and accumulating sizes:

  • Pass the file path to os.path.getsize and add the returned value to a running total. section 12.6.2
  • Combine it with os.walk, os.path.islink, and extension checks to measure selected files while excluding symlinks. section 12.6.2
  • Use pathlib.Path.stat().st_size for a pathlib-based alternative. section 12.3 section 12.6.2

Total the sizes of .test files

import os total_size = 0 for root, _, files in os.walk('.'): for file in files: path = os.path.join(root, file) if file.endswith('.test') and not os.path.islink(path): total_size += os.path.getsize(path) print(f"Total size of .test files: {total_size} bytes") section 12.6.2

import pathlib
cur_path = pathlib.Path("sample_data")
 
size = 0
for text_path in cur_path.rglob("*.test"):            #1
    if not text_path.is_symlink():                    #2
        size += text_path.stat().st_size              #3
        
print(size)

Compare the pathlib form, which obtains the same size through text_path.stat().st_size after recursively finding matching files. section 12.6.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines the return value and demonstrates recursive filtering, but does not develop implementation internals.
Examples
Demonstrates totaling non-symlink .test files and moving them to a backup directory.
What you can do after
Apply it via os.path.getsize to calculate aggregate sizes for files selected during directory traversal.
How it connects
Connects file-size measurement with os.walk, symbolic-link checks, extension filtering, file moving, and pathlib.

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.