tempfile.TemporaryDirectory context manager in Python 2.7

guettli picture guettli · Oct 10, 2013 · Viewed 18.6k times · Source

Is there a way to create a temporary directory in a context manager with Python 2.7?

with tempfile.TemporaryDirectory() as temp_dir:
    # modify files in this dir

# here the temporary diretory does not exist any more.

Answer

Nicholas Bishop picture Nicholas Bishop · Sep 22, 2016

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.