the temp module provides a namedtemporaryfile that can be reopened in the same process on any platform most platforms use the standard python tempfile namedtemporaryfile class but windows users are given a custom class this is needed because the python implementation of namedtemporaryfile uses the otemporary flag under windows which prevents the file from being reopened if the same flag is not provided 12 note that this does not address the more general issue of opening a file for writing and reading in multiple processes in a manner that works across platforms the custom version of namedtemporaryfile doesn t support the same keyword arguments available in tempfile namedtemporaryfile 1 https mail python orgpipermailpythonlist2005december336957 html 2 https bugs python orgissue14243 temporary file object constructor that supports reopening of the temporary file in windows unlike tempfile namedtemporaryfile from the standard library init doesn t support the delete buffering encoding or newline keyword arguments because close can be called during shutdown we need to cache os unlink and access it as self unlink only temporary file object constructor that supports reopening of the temporary file in windows unlike tempfile namedtemporaryfile from the standard library __init__ doesn t support the delete buffering encoding or newline keyword arguments because close can be called during shutdown we need to cache os unlink and access it as self unlink only
import os
import tempfile

from django.core.files.utils import FileProxyMixin

__all__ = (
    "NamedTemporaryFile",
    "gettempdir",
)


if os.name == "nt":

    class TemporaryFile(FileProxyMixin):
        

        def __init__(self, mode="w+b", bufsize=-1, suffix="", prefix="", dir=None):
            fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
            self.name = name
            self.file = os.fdopen(fd, mode, bufsize)
            self.close_called = False

        
        
        
        unlink = os.unlink

        def close(self):
            if not self.close_called:
                self.close_called = True
                try:
                    self.file.close()
                except OSError:
                    pass
                try:
                    self.unlink(self.name)
                except OSError:
                    pass

        def __del__(self):
            self.close()

        def __enter__(self):
            self.file.__enter__()
            return self

        def __exit__(self, exc, value, tb):
            self.file.__exit__(exc, value, tb)

    NamedTemporaryFile = TemporaryFile
else:
    NamedTemporaryFile = tempfile.NamedTemporaryFile

gettempdir = tempfile.gettempdir