Can't access temporary files created with tempfile

python, windows

Solution

This causes the IOError because the file can be opened only once after it is created.

The reason is because `NamedTemporaryFile` creates the file with `FILE_SHARE_DELETE` flag on Windows. On Windows when a file has been created/opened with specific share flag all subsequent open operations have to pass this share flag. It's not the case with Python's `open` function which does not pass `FILE_SHARE_DELETE` flag. See my answer on How to create a temporary file that can be read by a subprocess? question for more details and a workaround.

Problem

I am using `tempfile.NamedTemporaryFile()` to store some text until the program ends. On Unix is working without any issues but on Windows the file returned isn't accessible for reading or writing: python gives Errno 13. The only way is to set `delete=False` and manually delete the file with `os.remove()`. Why?

Original source

Related problems