How to Create Temporary File in Python

Jay Shaw Feb 02, 2024
  1. Create Temporary File in Python Using the tempfile Module
  2. Create a Named Temporary File in Python
  3. Create Temporary File in Python Using the mkstemp Function
  4. Create a Temporary Directory in Python
How to Create Temporary File in Python

This article explains how to create a temporary file and directory in Python. Temporary files in Python are generated using the tempfile module.

This article also explains four sub-functions of tempfile, which are TemporaryFile, NamedTemporaryFile, mkstemp, and TemporaryDirectory.

Create Temporary File in Python Using the tempfile Module

This function creates a securely created temporary file in Python, which returns a storage region that resembles a file that can be utilized temporarily. It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected).

The syntax to use this function to create a temporary file in Python is :

file = tempfile.TemporaryFile()
# 	OR
file = tempfile.TemporaryFile(
    mode="w+b",  # Remains as Default mode if not mentioned
    suffix=None,  # adds a suffix to file name
    prefix=None,  # adds prefix to file name
    # etc.
)

This temporary file in Python will be deleted from the filesystem upon context completion (with block) or file object destruction file.close(). The new file can be read and written to without being closed because the mode parameter’s default value is w+b.

It operates in binary mode to maintain consistency across all systems, regardless of the saved data. Some extra terms like buffering, encoding, errors, and newline are part of the python built-in function open(), which can be used inside the parameter.

The below program demonstrates how to create a temporary file in Python using TemporaryFile().

The first line of code imports the library package tmpfile. A variable filepath is created that uses the tempfile.TemporaryFile() function to create a temporary file.

Data is written inside the temporary file using the filepath.write() function. This parameter takes only a byte type value, so the literal b is added before the string.

The filepath.seek(0) function loads the file in the file stream starting from length 0.

The printing variable filepath shows the address of the object. To check the filename of the temporary file, the function filepath.name() is printed.

The function filepath.read() reads the data from the temporary file and then is printed. Lastly, the temporary file object is released using filepath.close().

import tempfile

filepath = tempfile.TemporaryFile()

filepath.write(b"Writing some stuff")
filepath.seek(0)

print(filepath)
print(filepath.name)

print(filepath.read())
filepath.close()

Output:

"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
<tempfile._TemporaryFileWrapper object at 0x00000285D92DAC50>
C:\Users\WIN10~1\AppData\Local\Temp\st.cq3d03ezloraine
b'Hello world!'

Process finished with exit code 0

Let’s look at another program.

Here the variable filepath uses three parameters of the TemporaryFile sub-function. The mode is set as w+b, which stands for reading and writing.

Also, a prefix st. and a suffix loarine is added to the filename. The data is written to the temporary, and the filename is printed.

import tempfile

filepath = tempfile.TemporaryFile(
    mode="w+b",
    prefix="st.",  # adds prefix to file name
    suffix="loraine",  # adds a suffix to file name
)

filepath.write(b"Hello world!")

print(filepath.name)

filepath.close()

It can be seen that the prefix and suffix have been added to the file name.

"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
C:\Users\WIN10~1\AppData\Local\Temp\st.kepthvu_loraine

Process finished with exit code 0

It can be seen that the temporary file had been explicitly closed at the end of the program. Doing this closes the file, but it does not delete it.

The filename can be displayed even after closing the file, but its content cannot be loaded.

Reading or writing to a closed temporary file in Python results in a Value Error, the same as any normal file.

import tempfile

filepath = tempfile.TemporaryFile(
    mode="w+b",
    prefix="st.",  # adds prefix to file name
    suffix="loraine",  # adds a suffix to file name
)

filepath.write(b"Hello world!")

filepath.close()

print(filepath.name)

filepath.write(b"Hello world!")

Output:

"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
C:\Users\WIN10~1\AppData\Local\Temp\st.f7n0s5a6loraine
Traceback (most recent call last):
  File "C:/Users/Win 10/main.py", line 14, in <module>
    filepath.write(b'Hello world!')
  File "C:\Python36\lib\tempfile.py", line 485, in func_wrapper
    return func(*args, **kwargs)
ValueError: write to closed file

Process finished with exit code 1

Create a Named Temporary File in Python

The only difference between this function and TemporaryFile() is that this one ensures that the file has a visible name in the file system. This name can be found the in the name attribute when the object is returned.

In UNIX, the same name can be used to open another temporary file even if the previous file is already open, but it is prohibited in Windows.

By default, the temporary file in Python is set to remove as soon as it is closed, but it can be turned off by setting delete = False. Similar to a regular file, this file-like object can be used in a statement.

The syntax to use this sub-function is:

tmp = tempfile.NamedTemporaryFile()
# 	OR
tmp = tempfile.NamedTemporaryFile(mode="w+b", delete=False, suffix=None, prefix=None)

To create a named temporary file in Python, use the below program.

This program imports two library packages here, os and tempfile. A temporary file is created using the variable tempo_file, the delete parameter is set to False, and a prefix and suffix are provided.

Inside the try block, the file object is printed using print(tempo_file). Then, the file name is printed using print(tempo_file.name).

The function tempo_file.write() is used to write inside this temporary file.

Inside the finally block, the file is closed using tempo_file.close(). Then using the os.unlink() function, the file’s name is unlinked from the file object.

import os
import tempfile

tempo_file = tempfile.NamedTemporaryFile(delete=False, prefix="Ice", suffix="cream")
try:
    print(tempo_file)
    print(tempo_file.name)
    tempo_file.write(b"Peacock is national bird of India")
finally:
    tempo_file.close()
    os.unlink(tempo_file.name)

Output:

"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
<tempfile._TemporaryFileWrapper object at 0x000001DE90935C18>
C:\Users\WIN10~1\AppData\Local\Temp\Icez5eghui0cream

Process finished with exit code 0

The delete parameter is turned False in the above program, which means if it is not implicitly closed, it remains open. If the delete parameter is set to True, then the filename cannot be accessed after the file is closed.

import os
import tempfile

tempo_file = tempfile.NamedTemporaryFile(delete=True)
try:
    print(tempo_file.name)
finally:
    tempo_file.close()
    os.unlink(tempo_file.name)

print(tempo_file.name)

Output:

"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/ain.py"
C:\Users\WIN10~1\AppData\Local\Temp\tmp6j3xxjzr
Traceback (most recent call last):
  File "C:/Users/Win 10/main.py", line 14, in <module>
    os.unlink(tempo_file.name)
FileNotFoundError: [WinError 2] The system cannot find the file specified:'C:\\Users\\WIN10~1\\AppData\\Local\\Temp\\tmp6j3xxjzr'

Process finished with exit code 1

A with block is helpful as it automatically closes the file.

import tempfile

with tempfile.TemporaryFile(delete=True) as tempo_file:
    print(tempo_file)
    print(tempo_file.name)
    tempo_file.write(b"Peacock is national bird of India")

print(tempo_file.read())

Output:

"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
<tempfile._TemporaryFileWrapper object at 0x0000027EB1C09390>
C:\Users\WIN10~1\AppData\Local\Temp\tmpzk_gpkau
Traceback (most recent call last):
  File "C:/Users/Win 10/main.py", line 11, in <module>
    print(tempo_file.read())
  File "C:\Python36\lib\tempfile.py", line 485, in func_wrapper
    return func(*args, **kwargs)
ValueError: read of closed file

Process finished with exit code 1

Create Temporary File in Python Using the mkstemp Function

This function provides the highest level of security feasible to create a temporary file in Python. Only the user ID that created the file has access to read and write it.

No one can execute the file if the platform employs permission bits to determine whether a file is executable. Even child processes do not inherit the file descriptor.

The syntax used for mkstemp is:

tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)

Unlike the function TemporaryFile(), the programmer must implicitly delete the temporary file when mkstemp() is used. The function has unique roles for the prefix, suffix, and dir parameters.

Let’s look at them.

The file name will end with a given suffix if it is not set to None; otherwise, there won’t be one. A dot must be placed at the beginning of the suffix if required because mkstemp() does not place one between the file name and the suffix.

The file name will start with a prefix if there is one instead of None; otherwise, a default prefix is used. The value returned from gettempprefix() or gettempprefixb() serves as the default, whichever program seems appropriate.

The dir stores the directory of the temporary file. A file will be created in a given directory if dir is not set to None; otherwise, a default directory is used.

The default directory is platform-dependent.

By altering the TMPDIR, TEMP, or TMP environment variables, the application user can override the default directory’s selection from that platform-specific list.

suffix, prefix, and dir must all have the same type if they are not set to None. If these are bytes, the name returned will be bytes rather than str.

Passing suffix=b will force bytes in the return value instead of its default behavior.

The file is opened in text mode if the text is specified and True. If it is set to False, the system opens the file in binary mode as default.

The program below creates a temporary file using mkstemp. The mkstemp function uses two arguments, the first is the identifier of the file, and the second is the filename.

Inside a try block, the file is made open using a with block through its handle. Then some data is written inside the file.

Inside the finally block, the file is implicitly deleted using os.unlink(filename).

import os
import tempfile

handle, filename = tempfile.mkstemp(suffix=".bat")
try:
    with os.fdopen(handle, "w") as f:
        f.write("signature")
        print(handle)
        print(filename)

finally:
    os.unlink(filename)

Output:

"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
3
C:\Users\WIN10~1\AppData\Local\Temp\tmp1yvy9j_c.bat

Process finished with exit code 0

Create a Temporary Directory in Python

This class makes a temporary directory safely. These objects can be used using a context manager like the with block.

Newly formed temporary directories and their contents are deleted from the memory upon context completion or temporary directory object destruction.

The returned object’s name attribute contains the directory name, which can be obtained. This name is given to the as clause’s target in the with statement (if there is one) when the returned object is used as a context manager.

For example:

with tempfile.TemporaryDirectory() as f:  # 'f' is the 'as' clause in this while statement
    print("Temporary directory is created", f)

Calling the cleanup() method will explicitly wipe up the directory. Any unhandled exceptions during explicit or implicit cleanup will be disregarded if ignore cleanup errors is true.

Any remaining removable items will be destroyed using the Best-Effort techniques.

To create a temporary directory, we can use the below Python program:

import tempfile

with tempfile.TemporaryDirectory() as f:
    print("Temporary directory is created", f)

Output:

"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
Temporary directory is created C:\Users\WIN10~1\AppData\Local\Temp\tmp1gk3c5z8

Process finished with exit code 0

This article has explained methods to create temporary files using the tempfile module in Python and its sub-functions.

Related Article - Python File