Permission Denied To Write To My Temporary File

Use the delete parameter as below:

tmpf = NamedTemporaryFile(delete=False)

But then you need to manually delete the temporary file once you are done with it.

tmpf.close()
os.unlink(tmpf.name)

Reference for bug: https://github.com/bravoserver/bravo/issues/111

regards, Vidyesh


NamedTemporaryFile actually creates and opens the file for you, there's no need for you to open it again for writing.

In fact, the Python docs state:

Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).

That's why you're getting your permission error. What you're probably after is something like:

f = tempfile.NamedTemporaryFile(mode='w') # open file
temp = f.name                             # get name (if needed)

Consider using os.path.join(tempfile.gettempdir(), os.urandom(24).hex()) instead. It's reliable, cross-platform, and the only caveat is that it doesn't work on FAT partitions.

NamedTemporaryFile has a number of issues, not the least of which is that it can fail to create files because of a permission error, fail to detect the permission error, and then loop millions of times, hanging your program and your filesystem.