using NamedTemporaryFile on windows

Tim Peters tim.peters at
Fri Dec 30 06:31:16 CET 2005

[Peter Hansen]
>>> What I don't understand is why you _can't_ reopen the NamedTemporaryFile
>>> under Windows when you can reopen the file created by mkstemp (and the
>>> files created by TemporaryFile are created by mkstemp in the first place).

[Lee Harr]
>> Are you saying you tried it and you actually can do what it says
>> you can't do?

[Peter Hansen]
> I don't think so.  I think I was saying that I can do exactly what it
> says I can, and can't do what it says I can't do, but that I don't
> understand why there is a difference between the two approaches given
> what else it says... (I hope that's clearer than it looks to me. ;-)

Because NamedTemporaryFile on Windows passes the Microsoft-specific
O_TEMPORARY flag, and mkstemp doesn't.  One consequence is that you
have to delete a temp file obtained from mkstemp yourself, but a
NamedTemporaryFile goes away by magic when the last handle to it is
closed.  Microsoft's I/O libraries do that cleanup, not Python.

Another consequence is that a file opened with O_TEMPORARY can't be
opened again (at least not via C stdio), not even by the process that
opened it to begin with.  AFAICT Microsoft never documented this, but
that's how it works.  Because you can't delete an open file on
Windows, temp files on Windows always have names visible in the
filesystem, and that's a potential "security risk".  _Presumably_ the
inability to open an O_TEMPORARY file again was a partially-baked
approach to eliminating that risk.

More information about the Python-list mailing list