brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's tempfile.TemporaryDirectory cleans up after itself

Python
~/tips/tip-python-tempfile-temporarydirectory

import tempfile, shutil

Get a scratch folder that disappears on its own when your code is done with it.

When a script needs somewhere to unpack an archive or build a file before moving it into place, I’d use tempfile.TemporaryDirectory instead of inventing a path in /tmp myself.

import tempfile, shutil
from pathlib import Path

with tempfile.TemporaryDirectory(prefix="backup-") as tmp:
    work = Path(tmp)
    shutil.unpack_archive("site.tar.gz", work)
    print(sorted(p.name for p in work.iterdir()))
# the folder and everything in it is gone here

The name is unique and the folder is created with permissions only your user can read, so two runs at the same time won’t trip over each other. When the with block ends, normally or through an exception, the whole tree is deleted.

The prefix is optional, but it makes the folder easy to recognise if you ever go looking while the script runs. There’s also dir= to put it on a different disk, which helps when /tmp is a small RAM disk and you’re unpacking something big.

Because the cleanup is automatic, anything you want to keep must be moved out before the block ends. If you’re debugging and want to look inside afterwards, pass delete=False (Python 3.12 and newer) and remove the folder yourself when you’re done.

Further reading: tempfile.TemporaryDirectory

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link