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)
Answer from paxdiablo on Stack Overflow
🌐
Python
bugs.python.org › issue22107
Issue 22107: tempfile module misinterprets access denied error on Windows - Python tracker
July 30, 2014 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/66305
Discussions

NamedTemporaryFile
Hi, I use the next code: with NamedTemporaryFile(delete=False) as tmp: wb.save(tmp.name) tmp.seek(0) return tmp.read() Without the flag ‘delete=False’ it has worked before, but now I get the error message ‘permission denied’ with wb.save. I had to add the flag ‘delete=False’ to ... More on community.viktor.ai
🌐 community.viktor.ai
1
0
August 23, 2022
Tempfiles are not working on Windows
Bug description On Windows, when pip-audit creates the virtual environment a permission error occurs. This is caused under the hood by a known bug in Python itself. However, there is a way to work ... More on github.com
🌐 github.com
3
July 6, 2023
NamedTemporaryFile function under windows
Hi, I tried to run the MUV inotebook and got some errors with [Errno 13] Permission denied when trying to read or write from temp file. I found the error online with the solution http://zachmoshe.c... More on github.com
🌐 github.com
9
August 29, 2017
How to access NamedTemporaryFile with Pandas?
Have you verified the user running the script has all the correct permissions? More on reddit.com
🌐 r/learnpython
3
3
June 19, 2025
🌐
GitHub
github.com › appveyor › ci › issues › 2547
Temporary files: Permission denied · Issue #2547 · appveyor/ci
July 31, 2018 - I am trying to write some temporary files using Python's NamedTemporaryFile and alike, and get errors: IOError: [Errno 13] Permission denied: 'c:\\projects\\python-can\\test\\__tmpdir__\\tmpj6uyhy.asc' This occurs in the python-can repo,...
Author   appveyor
🌐
SciVision
scivision.dev › python-tempfile-permission-error-windows
Python tempfile on Windows | Scientific Computing
April 16, 2024 - # the context manager attempts to recursively delete "tmpdir" on exit · If there is a PermissionError, the temporary directory remains until the operating system cleans up the temporary directory. Python tempfile.NamedTemporaryFile defaults for Python ≥ 3.12 handle file cleanup on Windows.
🌐
VIKTOR Community
community.viktor.ai › need help? ask here!
NamedTemporaryFile - Need help? Ask here! - VIKTOR Community
August 23, 2022 - Hi, I use the next code: with NamedTemporaryFile(delete=False) as tmp: wb.save(tmp.name) tmp.seek(0) return tmp.read() Without the flag ‘delete=False’ it has worked before, but now I get the error message ‘permission denied’ with wb.save. I had to add the flag ‘delete=False’ to make it work again.
🌐
GitHub
github.com › pypa › pip-audit › issues › 646
Tempfiles are not working on Windows · Issue #646 · pypa/pip-audit
July 6, 2023 - ERROR:pip_audit._virtual_env:internal pip failure: ERROR: Could not open requirements file: [Errno 13] Permission denied: 'C:\\Users\\Manrho\\AppData\\Local\\Temp\\82\\tmpnmkebs43' ERROR:pip_audit._cli: Failed to install packages: ['C:\\Users\\Manrho\\AppData\\Local\\Temp\\82\\tmp855pujcg\\Scripts''python.exe', ' -m', ' pip', ' install', ' --dry-run', '--report', 'C:\\Users\\Manrho\\AppData\\Local\\Temp\\82\\tmpm_c5v3cp', '-r', 'C:\\Users\\Manrho\\AppData\\Local\\Temp\\82\\tmpnmkebs43']
Author   pypa
🌐
GitHub
github.com › deepchem › deepchem › issues › 707
NamedTemporaryFile function under windows · Issue #707 · deepchem/deepchem
August 29, 2017 - I found the error online with the solution http://zachmoshe.com/2017/04/03/pickling-keras-models.html And adding delete=False to the 4 instances of NamedTemporaryFile in the file deepchem\hyper_init_.py from tempfile.NamedTemporaryFile() to ...
Author   deepchem
🌐
Reddit
reddit.com › r/learnpython › how to access namedtemporaryfile with pandas?
r/learnpython on Reddit: How to access NamedTemporaryFile with Pandas?
June 19, 2025 -

For some context, I have dozens of csv files in a directory that contain information that I need to process. One of the problems with this though, is that the csv files actually contain several different data sets, each with a different number of columns, column names, column data types, etc. As such, my idea was to preprocess each csv to extract just the lines that contain the data that I need, I can do this by just counting how many columns are in each line of the csv.

My idea was to go through each of the csvs that I need to process, extract the relevant lines from the csvs and write them to a Python NamedTemporaryFile from the tempfile module. Then, once all of the files have had the relevant data extracted, I would then read the data from the temp file into a pandas data frame that I could then work with. However, I keep running into a "Permission denied" error that I'm not entirely sure how to get around. Here is the code (with some sensitive information removed) that I'm working with:

import os
import tempfile
import pandas as pd

if __name__ == '__main__':
    # This is the directory that the csvs are stored in
    dir_path = r'\\My\Private\Directory'

    # get all the csv files and their full paths from the directory 
    files = [os.path.join(dir_path,f) for f in os.listdir(dir_path)]

    # A list of column names for the final pandas dataframe
    # this is just an example list, there are actually 46 columns in total
    columns = ['col1', 'col2']

    # open a named temporary file in the same directory the original csvs came from
    # then loop through all the lines in all the csvs and write the lines with the
    # correct number of columns to the temporary file
    with tempfile.NamedTemporaryFile(dir=dir_path, suffix='.csv', mode='w+') as temp_file:
        for file in files:
            with open(file, 'r') as f:
                for line in f.readlines():
                    if line.count(',') == 46:
                        temp_file.write(line)
        # here I try to read the temp file into the pandas dataframe 
        df = pd.read_csv(temp_file.name, names=columns, header=None, dtype=str)
    
    # However, after trying to read the temp file I get the error:
    # PermissionError: [Errno 13] Permission denied:
    # '\\\\My\\Private\\Directory\\tmps3m6jegs.csv'

    print(df)

As mentioned in the comments in the code block above, when I try the above code, everything seems to work fine up until I try to read the temp file with pandas and get the aforementioned "PermissionError".

In the "NamedTemporaryFile" function, I also tried setting the "delete" parameter to False, which means that the resulting temporary file that is created isn't automatically deleted when the "with" statement ends. When I did this, pandas could read the data from the temp file, but like I said, it doesn't delete the temp file afterwards, which kind of defeats the purpose of the temp file in the first place.

If anyone has any ideas as to what I could be doing wrong or potential fixes I would appreciate the help!

Find elsewhere
🌐
GitHub
github.com › allenai › olmocr › issues › 74
Temporary file permissions access denied in windows · Issue #74 · allenai/olmocr
March 2, 2025 - Running the pipeline in a windows environment results in an error due to permissions. Access is denied to the temporary files created during processing. I believe the delete=False flag has to be set for NamedTemporaryFile to allow use in a windows environment. python -m olmocr.pipeline ./localworkspace --pdfs tests/gnarly_pdfs/horribleocr.pdf
Author   allenai
🌐
Reddit
reddit.com › r/learnpython › unable to open an image i saved as a temp file.
r/learnpython on Reddit: Unable to open an image I saved as a temp file.
December 10, 2016 -
import tempfile
import requests
from PIL import Image
import time

url = "http://i.imgur.com/ANOJOwy.png"
r = requests.get(url) 
with tempfile.NamedTemporaryFile(mode="wb",delete=True) as jpg:
    jpg.write(r.content)
    name = str(jpg.name)
    img = Image.open(name)
    img.show()
    time.sleep(60)

The error:

PermissionError: [Errno 13] Permission denied: 'C:\\Users\\...\\AppData\\Local\\Temp\\tmppgywxdsc'

Edit:

os.startfile(name) works, but I have to choose a program to run it with everytime. Why doesn't PIL work?

🌐
CSDN
devpress.csdn.net › python › 630452487e66823466199c1a.html
Permission Denied To Write To My Temporary File_python_Mangs-Python
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)
🌐
Python
bugs.python.org › issue37477
Issue 37477: NamedTemporaryFile can hang on windows - Python tracker
July 1, 2019 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/81658
🌐
AppVeyor Support
help.appveyor.com › discussions › problems › 938-getting-permission-denied-errors-when-trying-to-make-a-temp-directory
Getting Permission Denied errors when trying to make a temp directory / Problems / Discussion Area - AppVeyor Support
October 23, 2014 - Try making a simple test reproducing the issue to isolate it. I'm not a C++ guru but sometimes permission denied error could mean something else. ... I'm experiencing similar issues using Python's tempfile library. I've tried changing the permissions of the directory to 777 using os.chmod but ...
🌐
GitHub
github.com › dolthub › doltpy › issues › 155
PermissionError: [Errno 13] Permission denied on Windows when writing to temp file · Issue #155 · dolthub/doltpy
June 4, 2021 - I think this stack overflow thread describes the issue at hand on windows: https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file · Basically this (Python docs): tempfile.NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None) This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked).
Author   dolthub
🌐
CSDN
devpress.csdn.net › python › 63045f837e6682346619ab2b.html
Permission denied when pandas dataframe to tempfile csv_python_Mangs-Python
August 23, 2022 - I've also tried changing the temp ... is no longer a temp file. ... I get the same error message as before. The file is not open anywhere else. Check your permissions and, according to this post, you can run your program as an administrator by right click and run as ...
🌐
pythontutorials
pythontutorials.net › blog › can-t-access-temporary-files-created-with-tempfile
Why Can't I Access Temporary Files Created with `tempfile.NamedTemporaryFile()` on Windows? Fixing Errno 13 Access Denied — pythontutorials.net
But on Windows, trying to access temp_file.name (e.g., by opening it in another process or even the same script) often triggers PermissionError: [Errno 13] Access denied. The "Access Denied" error stems from Windows’ strict file locking semantics, which differ from Unix-like systems. Here’s why it happens: On Windows, when tempfile.NamedTemporaryFile() creates a file, it opens it with exclusive access by default.
🌐
GitHub
github.com › PythonSanSebastian › docstamp › issues › 14
Permission denied when writing tempfile on windows · Issue #14 · PythonSanSebastian/docstamp
September 21, 2018 - C:\Users\Martin\AppData\Local\Temp\tmpsa4be55x.svg ERROR:docstamp.file_utils:Error writing to file in C:\Users\Martin\AppData\Local\Temp\tmpsa4be55x.svg Traceback (most recent call last): File "C:\Users\Martin\1-CAREM\3-Caratulas Manuales\python\python-3.7.0\lib\site-packages\docstamp\file_utils.py", line 192, in write_to_file with open(file_path, "wb") as f: PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Martin\\AppData\\Local\\Temp\\tmpsa4be55x.svg' ERROR:docstamp.template:Document of type <class 'docstamp.template.SVGDocument'> got an error when writing content.
Author   PythonSanSebastian
🌐
Django
code.djangoproject.com › ticket › 18744
#18744 (NamedTemporaryFile opened in read mode cannot be written to by another process on Windows) – Django
It uses NamedTemporaryFile, with the expectation that the Windows version will behave identically to the *nix version, as the documentation states. However, many external processes will fail with some sort of permission error when they try to write to the temporary file that was created via NamedTemporaryFile and not closed.
🌐
Python
docs.python.org › 3 › library › tempfile.html
tempfile — Generate temporary files and directories
On Windows, if delete_on_close is false, and the file is created in a directory for which the user lacks delete access, then the os.unlink() call on exit of the context manager will fail with a PermissionError. This cannot happen when delete_on_close is true because delete access is requested by the open, which fails immediately if the requested access is not granted. On POSIX (only), a process that is terminated abruptly with SIGKILL cannot automatically delete any NamedTemporaryFiles it created. Raises an auditing event tempfile.mkstemp with argument fullpath.
🌐
DNMTechs
dnmtechs.com › permission-denied-writing-to-temporary-file
Permission Denied: Writing to Temporary File – DNMTechs – Sharing and Storing Technology Knowledge
import tempfile try: # Create a temporary file temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False) # Write data to the temporary file temp_file.write("This is some sample data.") # Close the temporary file temp_file.close() # Print the path of the temporary file print("Temporary file path:", temp_file.name) except PermissionError: print("Permission denied: Unable to write to temporary file.") 1. Python tempfile module documentation: https://docs.python.org/3/library/tempfile.html