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.
Python provides a module known as tempfile, which makes creating and handling temporary files easier. This module provides a few methods to create temporary files and directories in different ways. tempfile comes in handy whenever you want to use temporary files to store data in a Python program.
This name is generally obtained from tempdir environment variable. On Windows platform, it is generally either user/AppData/Local/Temp or windowsdir/temp or systemdrive/temp. On linux it normally is /tmp. This directory is used as default value of dir parameter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With