CarpeNoctem
CarpeNoctem

Reputation: 5660

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.

Upvotes: 11

Views: 7270

Answers (2)

user2665694
user2665694

Reputation:

From the documentation of tempfile.TemporaryDirectory():

This function creates a temporary directory using mkdtemp() (the supplied arguments are passed directly to the underlying function). The resulting object can be used as a context manager (see With Statement Context Managers). On completion of the context (or destruction of the temporary directory object), the newly created temporary directory and all its contents are removed from the filesystem.

Upvotes: 6

Bill Lynch
Bill Lynch

Reputation: 81926

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.

Upvotes: 12

Related Questions