Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tempfile.TemporaryDirectory context manager in Python 2.7

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. 
like image 312
guettli Avatar asked Oct 10 '13 12:10

guettli


People also ask

Is Tempfile included in Python?

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.

Where is my python TEMP folder?

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.


1 Answers

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. 
like image 97
Nicholas Bishop Avatar answered Sep 19 '22 15:09

Nicholas Bishop