Does mkstemp open files only if they don't already exist?

Chris Angelico rosuav at
Tue Sep 1 16:57:45 CEST 2015

On Wed, Sep 2, 2015 at 12:45 AM, Steven D'Aprano <steve at> wrote:
> I assume the answer is "Yes", but is it safe to expect that
> tempfile.mkstemp() will only create a file that doesn't already exist? I
> presume that there's no chance of it over-writing an existing file (say,
> due to a race-condition).

It depends on OS support, but with that, yes, it is guaranteed to be
safe; the file is opened with an exclusivity flag. Check your system's
man pages for details, or here:

O_EXCL|O_CREATE makes an "atomic file creation" operation which will
fail if another process is doing the same thing. I'm not sure how
mkstemp() handles that failure, but my guess/expectation is that it
would pick a different file name and try again.


More information about the Python-list mailing list