python-3.xwindows-10temporary-filesfile-writing

Python tempfile with a context manager on Windows 10 leads to PermissionError: [Errno 13]


OS: Windows 10

Python: 3.6 (Anaconda)

I am trying to use a simple temporary file with a context manager to write a simple csv.

import csv
import tempfile

fp = tempfile.TemporaryFile()
with open(fp.name,'w',newline='') as f:
    csv_out = csv.writer(f)
    csv_out.writerow(['first_name','last_name'])
    csv_out.writerow(['foo','bar'])

Running this results in this permission error:

with open(fp.name,'w',newline='') as f:
E       PermissionError: [Errno 13] Permission denied: 'C:\\TEMP\\tmp2bqke7f6'

Changing the Windows permission status on the temp directory C:\TEMP\ to allow full access by all users does not help.

Per this post I tried running my Windows cmd as Admin, still did not work.


Solution

  • Searching for a similar problem (link), I found (and tested) a solution which works for your problem as well.

    You just need to add a delete=False argument in your fp = tempfile.TemporaryFile() line.

    It seems that the file actually gets created in that line, and then trying to open it and write in it a second time (with open(fp.name)...) forbids you do to so.