I think you're looking for a tempfile.NamedTemporaryFile.

import tempfile
with tempfile.NamedTemporaryFile() as tmp:
    print(tmp.name)
    tmp.write(...)

But:

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).

If that is a concern for you:

import os, tempfile
tmp = tempfile.NamedTemporaryFile(delete=False)
try:
    print(tmp.name)
    tmp.write(...)
finally:
    tmp.close()
    os.unlink(tmp.name)
Answer from Minras on Stack Overflow
🌐
Python
docs.python.org › 3 › library › tempfile.html
tempfile — Generate temporary files and directories
This module creates temporary files and directories. It works on all supported platforms. TemporaryFile, NamedTemporaryFile, TemporaryDirectory, and SpooledTemporaryFile are high-level interfaces which provide automatic cleanup and can be used as context managers.
Top answer
1 of 3
267

I think you're looking for a tempfile.NamedTemporaryFile.

import tempfile
with tempfile.NamedTemporaryFile() as tmp:
    print(tmp.name)
    tmp.write(...)

But:

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).

If that is a concern for you:

import os, tempfile
tmp = tempfile.NamedTemporaryFile(delete=False)
try:
    print(tmp.name)
    tmp.write(...)
finally:
    tmp.close()
    os.unlink(tmp.name)
2 of 3
107

There is a tempfile module for python, but a simple file creation also does the trick:

new_file = open("path/to/FILE_NAME.ext", "w")

Now you can write to it using the write method:

new_file.write('this is some content')

With the tempfile module this might look like this:

import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)

With mkstemp you are responsible for deleting the file after you are done with it. With other arguments, you can influence the directory and name of the file.


UPDATE

As rightfully pointed out by Emmet Speer, there are security considerations when using mkstemp, as the client code is responsible for closing/cleaning up the created file. A better way to handle it is the following snippet (as taken from the link):

import os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)

The os.fdopen wraps the file descriptor in a Python file object, that closes automatically when the with exits. The call to os.remove deletes the file when no longer needed.

People also ask

Where are Python temporary files stored?
By default: Linux/macOS → /tmp Windows → %TEMP% You can override this using tempfile.tempdir.
🌐
takovibe.com
takovibe.com › home › blog › python tempfile explained: temporary files, auto-deletion & common mistakes
Python tempfile Explained: Temporary Files, Auto-Deletion & Common ...
What is the difference between TemporaryFile and NamedTemporaryFile?
TemporaryFile → faster, no filename, auto-deleted NamedTemporaryFile → has a path, shareable with other processes
🌐
takovibe.com
takovibe.com › home › blog › python tempfile explained: temporary files, auto-deletion & common mistakes
Python tempfile Explained: Temporary Files, Auto-Deletion & Common ...
🌐
Heitor's Log
heitorpb.github.io › bla › pytmp
Temporary files and directories in Python | Heitor's log
Python Standard Library has a module to work with temporary files and directories: tempfile. This module handles creating the files/directories, naming them, and cleaning-up after done.
🌐
Read the Docs
python.readthedocs.io › fr › stable › library › tempfile.html
11.6. tempfile — Generate temporary files and directories — documentation Python 3.6.1
This module creates temporary files and directories. It works on all supported platforms. TemporaryFile, NamedTemporaryFile, TemporaryDirectory, and SpooledTemporaryFile are high-level interfaces which provide automatic cleanup and can be used as context managers.
🌐
Real Python
realpython.com › ref › stdlib › tempfile
tempfile | Python Standard Library – Real Python
The Python tempfile module provides a simple way to create temporary files and directories.
🌐
Python.org
discuss.python.org › ideas
Create temporary files in a temporary directory - Ideas - Discussions on Python.org
January 16, 2024 - Often, I find myself needing to create multiple temporary files that are related. It would be nice if tempfile.TemporaryDirectory could make that easier for me using something like this: with tempfile.TemporaryDirectory() as temp_dir: fd1, temp_file1_path = temp_dir.mkstemp() fd2, temp_file2_path = temp_dir.mkstemp() # Do something with the files...
🌐
GeeksforGeeks
geeksforgeeks.org › python › create-temporary-files-and-directories-using-python-tempfile
Create temporary files and directories using tempfile - GeeksforGeeks
July 15, 2025 - Python tempfile module allows you to create a temporary file and perform various operations on it. Temporary files may be required when we need to store data temporarily during the program's execution or when we are working with a large amount ...
Find elsewhere
🌐
W3Schools
w3schools.com › python › ref_module_tempfile.asp
Python tempfile Module
Python Examples Python Compiler ... · ❮ Standard Library Modules · Create a temporary file and directory: import tempfile with tempfile.TemporaryFile(mode='w+') as f: f.write('Hello from Emil') f.seek(0) print(f'Content: ...
🌐
TakoVibe
takovibe.com › home › blog › python tempfile explained: temporary files, auto-deletion & common mistakes
Python tempfile Explained: Temporary Files, Auto-Deletion & Common Mistakes | Rahul Beniwal | TakoVibe
August 21, 2025 - ✔️ This creates an unnamed temporary file in w+t mode (write + text), allowing both reading and writing. ... 👉 Always prefer context managers so Python cleans up the file automatically, even if an exception occurs.
🌐
Adam Johnson
adamj.eu › tech › 2024 › 12 › 30 › python-temporary-files-directories-unittest
Python: create temporary files and directories in unittest - Adam Johnson
December 30, 2024 - The suffix is set to .html, which ensures the created file has that suffix. This isn’t mandatory, but it can make debugging easier. For example, if you need to open the file, it will open with its default program. ... from tempfile import TemporaryDirectory from unittest import TestCase class ExampleTests(TestCase): def test_example(self): temp_dir = self.enterContext(TemporaryDirectory()) # Write to a file with open(f"{temp_dir}/apple.html", "w") as temp_file: temp_file.write("<h1>Cosmic Crisp</h1>") # Read from the file with open(f"{temp_dir}/apple.html", "r") as temp_file: result = temp_file.read() self.assertEqual(result, "<h1>Cosmic Crisp</h1>")
🌐
Readthedocs
anyio.readthedocs.io › en › stable › tempfile.html
Asynchronous Temporary File and Directory — AnyIO 4.14.2 documentation
from anyio import mkstemp, mkdtemp, gettempdir, run import os async def main(): fd, path = await mkstemp(suffix=".txt", prefix="mkstemp_", text=True) print(f"Created temp file: {path}") temp_dir = await mkdtemp(prefix="mkdtemp_") print(f"Created temp dir: {temp_dir}") print(f"Default temp dir: {await gettempdir()}") os.remove(path) run(main) Note · Using these functions requires manual cleanup of the created files and directories. See also · Python Standard Library: tempfile (official documentation)
🌐
TutorialsPoint
tutorialspoint.com › how-to-create-a-unique-temporary-file-name-using-python
How to create a unique temporary file name using Python?
June 5, 2025 - The Python os.tmpnam() method returns a unique path name. The following example shows the usage of tmpnam() method. import os, sys # Temporary file generated in current directory tmpfn = os.tmpnam() print ("This is the unique path:") print (tmpfn)
🌐
Medium
medium.com › data-engineers-notes › using-tempfile-module-in-python-750aa1f285e0
Using tempfile module in Python
August 6, 2024 - Whether you want to store intermediate results, manage temp data during execution or just test things out, it can help you by abstracting file creation and cleaning-up operations. In the a quick walk-through below, we’re looking at the following functions: - TemporaryFile : creates an anonymous temporary file - NameTemporaryFile: creates a named temp file which we can use in multiple contexts - TemporaryDirectory: creates a temporary directory (in which we also can create temp files).
🌐
Esri Community
community.esri.com › t5 › python-questions › managing-temp-files-when-using-arcpy-mp › td-p › 1478194
Managing Temp files when using arcpy.mp.ArcGISProj... - Esri Community
June 5, 2024 - As the Map Series can be hundreds of pages and the WMS services generate many large png files, I have found that the Temp directory ArcGIS Pro uses is filling the disk to 100%. When ArcGIS Pro is opened via desktop, the Temp directory gets created by default in C:\Users\<username>\AppData\Local\Temp\ArcGISProTemp<random number>. When ArcGIS Pro is closed this directory is deleted.
🌐
GitHub
github.com › python-trio › trio › issues › 1931
[Question] What is the best way to create temp files and directories? · Issue #1931 · python-trio/trio
March 17, 2021 - Normally I would use tempfile module. But I was wondering if there's an async (trio compatible) alternative. Thanks in advance
Author   python-trio
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-tempfile-module
Python tempfile module - GeeksforGeeks
December 11, 2020 - The file is opened in w+b (both read and write to the open file)mode by default. This function creates a temporary file in the temp directory and returns a file object
🌐
Conda
docs.conda.io › projects › conda › en › latest › user-guide › configuration › temp-files.html
Configuring Temporary File Locations — conda 26.5.4.dev108 documentation
If none of these environment variables are set, Python falls back to platform-specific default locations: Windows: C:\TEMP, C:\TMP, \TEMP, \TMP (in that order) Unix/Linux/macOS: /tmp, /var/tmp, /usr/tmp (in that order) All platforms: As a last resort, the current working directory ... # For current session export TMPDIR=/path/to/writable/tmp mkdir -p $TMPDIR # To make permanent, add to ~/.bashrc or equivalent shell profile file echo 'export TMPDIR=/path/to/writable/tmp' >> ~/.bashrc # For a single command TMPDIR=/path/to/writable/tmp conda install package_name
🌐
pytest
docs.pytest.org › en › stable › how-to › tmp_path.html
How to use temporary directories and files in tests - pytest documentation
Python version support · Sponsor · pytest for enterprise · License · Contact channels · Useful links · pytest @ PyPI · pytest @ GitHub · Issue Tracker · PDF Documentation · Back to top · You can use the tmp_path fixture which will provide a temporary directory unique to each test ...