11

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.

1
  • 2
    The last sentence of the docs is pretty clear
    – user2665694
    May 25, 2011 at 18:29

2 Answers 2

11

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.

6

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.

3
  • Feel free to downvote me if you won't read the last sentence. The last sentence explains the asked question very clearly.
    – user2665694
    May 25, 2011 at 18:32
  • I don't remember reading any user requirements during SO registration that required I be of a certain level of proficiency with programming or development. Not all of us do this for a living nor should such be assumed. I'm merely asking for someone to further explain what's documented "clearly" to some. May 25, 2011 at 19:14
  • So with mkdtemp a dirname is returned to be used. How do I create a subdir using TemporaryDirectory and write files to it. Do I use the TemporaryDirectory object as if it was a dirname? The necessary back information that you are not even questioning doesn't exist for some of us. May 25, 2011 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.