Skip to content Skip to sidebar Skip to footer

How To Remove Tempfile In Python

What is the best way to remove a tempfile? Is there a builtin method for it? For example: self.tempdir = tempfile.mkdtemp() rm self.tempdir ?

Solution 1:

Removing a temporary directory is the same as removing any other directory: just call os.rmdir if you're sure you've already emptied it out (and consider it an error if it's not empty), or shutil.rmtree if not.

If you're using 3.2 or later, it's much simpler to just create the temporary directory with TemporaryDirectory instead of mkdtemp. That takes care of all the fiddly edge cases, in a nicely cross-platform way, so you don't have to worry about them. (If you were creating a temporary file, as your question title suggests, it's even more worth using the higher-level APIs like TemporaryFile or NamedTemporaryFile.) For example:

with tempfile.TemporaryDirectory() as tempdir:
    do_stuff_with(tempdir)
    # deletes everything automatically at end of with

Or, if you can't put it inside a with statement:

defmake_tempdir(self):
    self.tempdir = tempfile.TemporaryDirectory()
defremove_tempdir(self):
    self.tempdir.cleanup()

In fact, even for 2.7 or 3.1, you might want to consider borrowing the source to 3.5's TemporaryDirectory class and using that yourself (or looking for a backport on PyPI, if one exists).

Post a Comment for "How To Remove Tempfile In Python"