Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Hands on the tempfile Module in Python

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

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. mkstemp() and mkdtemp() are lower-level functions which require manual cleanup.

tempfile.TemporaryFile

11
0
b'how are you'
_io.BufferedRandom
58
b'how are you'

tempfile.TemporaryDirectory

Notice that after finish of the with block, the temporary directory is removed automatically.

/tmp/tmpwnml8m3t
str
False

tempfile.mkstemp

  1. The returned file descriptor must be closed (using os.close manually or using a contextual manager) to avoid leak of resource!

  2. The suffix option can be used to create a temporary file with a specific file extension.

Below are examples of using tempfile.mkstemp in correct ways. The first example close the file descriptor manually using os.close. The second example close the file automatically using the with block.

/tmp/tmp90pu002w
how are you
/tmp/tmp4shh3pnx
I am fine.

Create a temporary SQL file.

(57, '/tmp/tmpzjxy8tg9.sql')

tempfile.mkdtemp

'/tmp/tmpwusvuq3c'

Set a Different Temporary Directory

In certain situations, you might want to set a different temporary directory than the default one. For example, if an application leverages temporary files/dirs extensively while there’s very limited space in the temporary directory (commonly seen when the application is running in a container environment on cloud), you can run into “OSError: No space left on the device”. An easy fix of this issue is to set environment variables to point the temporary directory to an existing directory with enough space which is writable by the user. The code below illustrate how to change the default temporary directory. Notice that tempfile.tempdir = None is added to clear possible caching. For more details, please refer to tempfile.gettempdir .

(57, '/Users/dclong/tmptci7lsir')