typestar

Temporary files and trees in Python

Scratch space that cleans itself up, and the tree operations worth knowing.

import shutil
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as name:
    workspace = Path(name)
    (workspace / "src").mkdir()
    (workspace / "src" / "one.txt").write_text("hello")

    shutil.copytree(workspace / "src", workspace / "copy")
    print(sorted(p.name for p in (workspace / "copy").iterdir()))

    shutil.make_archive(str(workspace / "bundle"), "zip", workspace / "src")
    print((workspace / "bundle.zip").exists())

print(Path(name).exists())

How it works

  1. TemporaryDirectory removes itself at the end of the block.
  2. NamedTemporaryFile has a path other processes can open.
  3. shutil copies, moves and deletes whole trees.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
465
Tokens
139
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 2 of 4 in Files & archives, step 27 of 41 in Domain tools.

← Previous Next →