- 1 year ago
How to let mktmpdir delete directory on Windows?
Comment
1 / 1
The mktmpdir
function in Python's tempfile
module does not automatically delete the directory it creates on Windows. However, you can manually delete the temporary directory by using the shutil.rmtree
function from the shutil
module. Here's an example:
pythonimport tempfile
import shutil
def create_temp_directory():
temp_dir = tempfile.mkdtemp()
print("Temporary directory created:", temp_dir)
# Use the temporary directory...
# Delete the temporary directory
shutil.rmtree(temp_dir)
print("Temporary directory deleted")
# Call the function to create and delete the temporary directory
create_temp_directory()
In this example, the mkdtemp
function creates a temporary directory using the tempfile
module. After you finish using the temporary directory, you can delete it using shutil.rmtree
by passing the path of the temporary directory as an argument. The rmtree
function recursively removes the directory and all its contents.
Make sure to use this approach responsibly and ensure that you have finished using the temporary directory before deleting it, as the data inside will be permanently lost.