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
TemporaryDirectoryremoves itself at the end of the block.NamedTemporaryFilehas a path other processes can open.shutilcopies, moves and deletes whole trees.
Keywords and builtins used here
asforprintsortedstrwith
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.
Step 2 of 4 in Files & archives, step 27 of 41 in Domain tools.