tempfile.TemporaryDirectory context manager in Python 2.7

Another option is the “backports.tempfile” package on pypi: https://pypi.python.org/pypi/backports.tempfile

Quoting the project’s description: “This package provides backports of new features in Python’s tempfile module under the backports namespace.”

Install with:

pip install backports.tempfile

Then use it in your script:

from backports import tempfile
with tempfile.TemporaryDirectory() as temp_dir:
    # modify files in this dir
# here the temporary directory does not exist any more.

Leave a Comment