On this page
  1. stat
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Marking a Generated Script Executable (Preserving Existing Bits)
  7. Gotchas & Boundaries
  8. Common Functions
  9. Constants & Attributes

stat

Prev: ssl | Up: stdlib_module | Next: statistics
Rel: pathlib, os, io, time, fileinput
Ref: docs.python.org โ€” stat
Tags: #public #python3 #stdlib


Import

import stat

Overview

Constants and helper functions for interpreting os.stat() / Path.stat() st_mode bitmasks (S_ISREG, S_ISDIR, S_ISLNK, S_IMODE, filemode, S_IRUSR, S_IWUSR, S_IXUSR). Use stat to inspect POSIX permissions, format ls -l-style mode strings, or set executable/owner-only permissions cleanly without opaque octal bit math.

Quick Start

import os
from pathlib import Path
import stat
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    p = Path(tmp) / "secret.key"
    p.write_text("token", encoding="utf-8")
    p.chmod(stat.S_IRUSR | stat.S_IWUSR)  # 0o600 (owner read/write only)
    mode = p.stat().st_mode
    assert stat.S_ISREG(mode) and stat.S_IMODE(mode) == 0o600
    assert stat.filemode(mode) == "-rw-------"

Implementation Walkthrough

1. Marking a Generated Script Executable (Preserving Existing Bits)

from pathlib import Path
import stat

def make_executable(path: Path) -> None:
    current = path.stat().st_mode
    path.chmod(current | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)

Gotchas & Boundaries

Common Functions

Constants & Attributes

Linked from

Related notes