Fix Python tempfile PermissionError on Windows

Python tempfile is normally robust but has some corner cases on Windows. A common issue is that on exiting a tempfile context manager, PermissionError is thrown on Windows. This can happen when non-writable files are placed into a tempfile.TemporaryDirectory such as cloning a Git directory into the TemporaryDirectory.


A common workaround is to simply not use the tempfile context manager, instead manually deleting the temporary directory when done:

from pathlib import Path
import tempfile

temp_dir = tempfile.TemporaryDirectory()
temp_path = Path(

# do stuff in temporary directory

# when done with temporary directory
except PermissionError:

If there is a PermissionError, the temporary directory remains until the operating system cleans up the temporary directory.