Reputation: 110382
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 ?
Upvotes: 2
Views: 7680
Reputation: 365915
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:
def make_tempdir(self):
self.tempdir = tempfile.TemporaryDirectory()
def remove_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).
Upvotes: 6