On this page
  1. os.replace
  2. Import
  3. Signature & Overview
  4. Usage
  5. Gotchas
  6. REPL Inspect

os.replace

Prev: os.rename | Up: os | Next: os.rmdir
Rel: os.abort, os.access, os.chdir, os.chmod
Ref: docs.python.org — os.replace
Tags: #public #python3 #stdlib #os


Import

import os
from os import replace

Signature & Overview

os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)

Rename a file or directory, overwriting the destination.

Usage

import os
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    tmp_file = Path(tmp) / "data.tmp"
    target = Path(tmp) / "data.json"
    target.write_text("old", encoding="utf-8")
    tmp_file.write_text("new", encoding="utf-8")
    os.replace(tmp_file, target)
    assert target.read_text(encoding="utf-8") == "new"

Gotchas

REPL Inspect

from os import replace
help(replace)

Linked from

Related notes