How to delete a directory created with tempfile.mkdtemp?

I have a python program that creates temporary directories under /temp by using tempfile.mkdtemp. Unfortunately, the Python program did not delete the directory after using it. So now the disk space is low.

Questions:

  1. How do I delete the temporary directories left under /temp manually? I tried to delete them manually but got "permission denied" error.
  2. In the Python program, how to delete temp directory after using them?

tempfile — Generate temporary files and directories, The file is created securely, using the same rules as mkstemp() . It will be the user of mkstemp() is responsible for deleting the temporary file when done with it. import errno import shutil import tempfile try: tmp_dir = tempfile.mkdtemp () # create dir # do something finally: try: shutil.rmtree (tmp_dir) # delete directory except OSError as exc: if exc.errno != errno.ENOENT: # ENOENT - no such file or directory raise # re-raise exception.

Read the documentation, it's simple. ;) From the docs: the directory is readable, writable, and searchable only by the creating user ID.

To delete temp directory try something like this:

import errno
import shutil
import tempfile

try:
    tmp_dir = tempfile.mkdtemp()  # create dir
    # ... do something
finally:
    try:
        shutil.rmtree(tmp_dir)  # delete directory
    except OSError as exc:
        if exc.errno != errno.ENOENT:  # ENOENT - no such file or directory
            raise  # re-raise exception

Also you can try tempdir package or see its sources.

11.5. tempfile — Generate temporary files and directories, Temporary file names created by this module no longer contain the process ID; The user of mkdtemp() is responsible for deleting the temporary directory and  The directory is readable, writable, and searchable only by the creating user ID. The user of mkdtemp() is responsible for deleting the temporary directory and its contents when done with it. The prefix, suffix, and dir arguments are the same as for mkstemp(). mkdtemp() returns the absolute pathname of the new directory.

I have had the same/similar problem using TemporaryDirectory() which is basically covering the functionality you defined above.

My problem was due to the usage of the temporary directory. I used to populate the content by cloning a git repository, it happened that there were read-only files created during the process and with a normal exit these read-only temp files were causing the complete temporary directory to stay there.

Did inherit the TemporaryDirectory to my own class and did override the class method _cleanup with the following code.

The code before super() might be optimized but for me, the performance was not the problem.

I did use the force and read the source of "tempfile"

import tempfile
import shutil
import stat 

class myTempDir(tempfile.TemporaryDirectory):
    @classmethod
    def _cleanup(self,name, warn_message):
        for root, dirs, files in os.walk(name):
            for fname in files:
                full_path = os.path.join(root, fname)
                os.chmod(full_path ,stat.S_IWRITE)
        super()

Solution worked for Windows 10 with Python 3

Create, use, and remove temporary files securely, Safely creating a temporary file or directory means following a number of tempfile.SpoolTemporaryFile. tempfile.mkstemp. tempfile.mkdtemp  If you use this in a test be sure to remove (shutil.rmtree) the directory because it's not automatically deleted after use. "The user of mkdtemp() is responsible for deleting the temporary directory and its contents when done with it."

I think the user is responsible for deleting the temporary directory and its content created by using tempfile.mkdtemp(). it will not deleted automatically just like temporary file. There are many ways you can delete the directory

If the directory is empty you can use

`os.removedirs or os.rmdir`

Note it can be used only if the directory is empty otherwise will raise

OSError

This will delete the entire directory path:

import shutil    
shutil.rmtree('/path/to/your/dir/')

be careful while using this, it will delete the whole directory and files inside it.

tempfile.mkdtemp Python Example, This page provides Python code examples for tempfile.mkdtemp. should not prevent # us from removing the directory it was created in. try: os.rmdir(dir) except​:  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.

Python tempfile, Temporary directories can be created using the tempfile.mkdtemp() function: manager, deleting the created temporary directory when the with block exits: import os import tempfile directory_name = tempfile. mkdtemp print directory_name # Clean up the directory yourself os. removedirs (directory_name) Since the directory is not “opened” per se, you have to remove it yourself when you are done with it.

The Python tempfile Module, This module provides a few methods to create temporary files and directories in i.e. it will create one file, use it to store some data, and then delete it after use. The tempfile.tempdir variable holds the default location for all temporary files. The mkstemp function in the tempfile module returns a tuple of 2 values:. an OS-level handle to an open file (as would be returned by os.open()) the absolute pathname of that file.

How to create temporary directory in Python – TechOverflow, Check out How to create a self-deleting temporary directory in Python for an tempfile.mkdtemp() will automatically create that directory. To remove a directory that contains other files or directories, use the following command. In the example above, you would replace "mydir" with the name of the directory you want to delete. Executing the command would recursively delete all files and subdirectories in that directory.

Comments
  • I don't think the OP's question was understood. The suggested code is a good example of what you should write in your program to clear out the temp dirs created. However, what if you application crashes (hard) without the chance to run that clean-up code? Then you'll have a temp dir kicking around that can only be deleted by the original process that created it (at least that what the docs seem to indicate) -- how is one supposed to clean that up?
  • Did you try to use the root account/admin?
  • Regarding 1 (deleting manually): it's a permissions problem: fix the permissions and delete, e.g.: chmod -R +w /tmp/tmp0ytcxm9c && rm -fr /tmp/tmp0ytcxm9c (if this is a permission error, you need to be the user that ran the program, or root).
  • You could also use backports.tempfile
  • this does not seem to be working. I got "Permission denied" error when running it. Also, I have many tmp directories on disk that I want to delete. I can not manually delete them also. What is the proper way to delete trees created by mkdtemp? thanks.
  • Maybe the problem in the value of umask on your system? You can see it in the umask command output, try to change it to 022 by executing: umask 022 and then try my code again.
  • FWIW, your answer is nicer than the documentation.
  • This is a good answer. Note, however, that the tempdir doc link is currently dead.