Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: differences between tempfile.mkdtemp and tempfile.TemporaryDirectory

I need to create a temp directory that will house another named directory and subfiles. In the end the named directory and subfiles will be appended to a tarball and the temp directory can be removed. Was initially going to use mkdtemp() but it looks like the TemporaryDirectory() method removes itself? Can someone explain the differences.

like image 460
CarpeNoctem Avatar asked May 25 '11 17:05

CarpeNoctem


People also ask

What is Tempfile Mkdtemp?

tempfile. mkdtemp(suffix=None, prefix=None, dir=None) Creates a temporary directory in the most secure manner possible. There are no race conditions in the directory's creation. The directory is readable, writable, and searchable only by the creating user ID.

What does Tempfile mean in Python?

Tempfile is a Python module used in a situation, where we need to read multiple files, change or access the data in the file, and gives output files based on the result of processed data. Each of the output files produced during the program execution was no longer needed after the program was done.

When should you use Tempfile?

In my view, you should use tempfile when you need to create a file but don't care about its name. You can have the file deleted automatically when you're done or saved, if you wish. It can also be visible to other programs or not. Save this answer.

Where is Tempfile stored python?

Practical Data Science using Python They are created in special temp directories that are defined by operating system file systems. For example, under Windows the temp folder resides in profile/AppData/Local/Temp while in linux the temporary files are held in /tmp directory.


1 Answers

You are correct in that the only real difference is that TemporaryDirectory will delete itself when it is done. It will let you do something like:

with tempfile.TemporaryDirectory() as dir:
   do_stuff_with(dir)

when you leave the scope of the with, the temporary directory will be deleted. With mkdtemp, you would need to do that manually.

like image 119
Bill Lynch Avatar answered Nov 02 '22 15:11

Bill Lynch