Library contents

Python Path.stat

Read size and type information for one file.

A simple example

Path.stat

  1. Start with A regular file containing ASCII AB
  2. Do this Measure its length
  3. Result 2 bytes
Each ASCII character occupies one byte and this file has no trailing newline.

Syntax

Python syntax
info = receipt.stat()
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Read a receipt catalog card

An archive is adding a fresh receipt to its catalog. Inspect the stored metadata to find its byte size and confirm that the entry is a regular file before recording it on the card.

Result4
lesson.py
from pathlib import Path
from tempfile import TemporaryDirectory
import stat

with TemporaryDirectory() as folder:
    base = Path(folder)
    receipt = base / "receipt"
    receipt.write_bytes(b"paid")
    info = receipt.stat()
    if stat.S_ISREG(info.st_mode):
        print(info.st_size)
Output
4

The ASCII word paid has four bytes and the record is a regular file.

Advertisements

Prepare a gallery label

A curator stores a short UTF-8 caption beside an exhibit. Read the size field on the saved file. How many bytes did these ASCII characters occupy without a trailing newline?

GivenFile contents “clay”
Worked result4

Prepare a studio handover

A stage manager saves a two-word instruction for the next shift. Read the size field on the saved file. How many bytes did these ASCII characters occupy without a trailing newline?

GivenFile contents “ring bell”
Worked result9

What to watch for

Metadata can change between inspection and later use.

Documentation for Path.stat