4

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.

Cale Sweeney
  • 1,014
  • 1
  • 15
  • 37
  • Possible duplicate of https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file – CDuvert Mar 08 '22 at 13:29
  • 1
    @CDuvert I think they are very similar but the link above deals with a NamedTemporaryFile. Mine addresses the TemporaryFile. It is good to have both for reference. See here for details: https://docs.python.org/3/library/tempfile.html – Cale Sweeney Mar 09 '22 at 14:21
  • Python 3.9: `with TemporaryDirectory() as tmpdir:` – matanster Mar 13 '23 at 14:20

1 Answers1

4

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.

Dositej
  • 114
  • 5