1:mod:`tempfile` --- Generate temporary files and directories
2============================================================
3
4.. module:: tempfile
5   :synopsis: Generate temporary files and directories.
6
7.. sectionauthor:: Zack Weinberg <[email protected]>
8
9**Source code:** :source:`Lib/tempfile.py`
10
11.. index::
12   pair: temporary; file name
13   pair: temporary; file
14
15--------------
16
17This module creates temporary files and directories.  It works on all
18supported platforms. :class:`TemporaryFile`, :class:`NamedTemporaryFile`,
19:class:`TemporaryDirectory`, and :class:`SpooledTemporaryFile` are high-level
20interfaces which provide automatic cleanup and can be used as
21context managers. :func:`mkstemp` and
22:func:`mkdtemp` are lower-level functions which require manual cleanup.
23
24All the user-callable functions and constructors take additional arguments which
25allow direct control over the location and name of temporary files and
26directories. Files names used by this module include a string of
27random characters which allows those files to be securely created in
28shared temporary directories.
29To maintain backward compatibility, the argument order is somewhat odd; it
30is recommended to use keyword arguments for clarity.
31
32The module defines the following user-callable items:
33
34.. function:: TemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)
35
36   Return a :term:`file-like object` that can be used as a temporary storage area.
37   The file is created securely, using the same rules as :func:`mkstemp`. It will be destroyed as soon
38   as it is closed (including an implicit close when the object is garbage
39   collected).  Under Unix, the directory entry for the file is either not created at all or is removed
40   immediately after the file is created.  Other platforms do not support
41   this; your code should not rely on a temporary file created using this
42   function having or not having a visible name in the file system.
43
44   The resulting object can be used as a context manager (see
45   :ref:`tempfile-examples`).  On completion of the context or
46   destruction of the file object the temporary file will be removed
47   from the filesystem.
48
49   The *mode* parameter defaults to ``'w+b'`` so that the file created can
50   be read and written without being closed.  Binary mode is used so that it
51   behaves consistently on all platforms without regard for the data that is
52   stored.  *buffering*, *encoding*, *errors* and *newline* are interpreted as for
53   :func:`open`.
54
55   The *dir*, *prefix* and *suffix* parameters have the same meaning and
56   defaults as with :func:`mkstemp`.
57
58   The returned object is a true file object on POSIX platforms.  On other
59   platforms, it is a file-like object whose :attr:`!file` attribute is the
60   underlying true file object.
61
62   The :py:data:`os.O_TMPFILE` flag is used if it is available and works
63   (Linux-specific, requires Linux kernel 3.11 or later).
64
65   On platforms that are neither Posix nor Cygwin, TemporaryFile is an alias
66   for NamedTemporaryFile.
67
68   .. audit-event:: tempfile.mkstemp fullpath tempfile.TemporaryFile
69
70   .. versionchanged:: 3.5
71
72      The :py:data:`os.O_TMPFILE` flag is now used if available.
73
74   .. versionchanged:: 3.8
75      Added *errors* parameter.
76
77
78.. function:: NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None)
79
80   This function operates exactly as :func:`TemporaryFile` does, except that
81   the file is guaranteed to have a visible name in the file system (on
82   Unix, the directory entry is not unlinked).  That name can be retrieved
83   from the :attr:`name` attribute of the returned
84   file-like object.  Whether the name can be
85   used to open the file a second time, while the named temporary file is
86   still open, varies across platforms (it can be so used on Unix; it cannot
87   on Windows).  If *delete* is true (the default), the file is
88   deleted as soon as it is closed.
89   The returned object is always a file-like object whose :attr:`!file`
90   attribute is the underlying true file object. This file-like object can
91   be used in a :keyword:`with` statement, just like a normal file.
92
93   On POSIX (only), a process that is terminated abruptly with SIGKILL
94   cannot automatically delete any NamedTemporaryFiles it created.
95
96   .. audit-event:: tempfile.mkstemp fullpath tempfile.NamedTemporaryFile
97
98   .. versionchanged:: 3.8
99      Added *errors* parameter.
100
101
102.. class:: SpooledTemporaryFile(max_size=0, mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)
103
104   This class operates exactly as :func:`TemporaryFile` does, except that
105   data is spooled in memory until the file size exceeds *max_size*, or
106   until the file's :func:`fileno` method is called, at which point the
107   contents are written to disk and operation proceeds as with
108   :func:`TemporaryFile`.
109
110   The resulting file has one additional method, :func:`rollover`, which
111   causes the file to roll over to an on-disk file regardless of its size.
112
113   The returned object is a file-like object whose :attr:`_file` attribute
114   is either an :class:`io.BytesIO` or :class:`io.TextIOWrapper` object
115   (depending on whether binary or text *mode* was specified) or a true file
116   object, depending on whether :func:`rollover` has been called.  This
117   file-like object can be used in a :keyword:`with` statement, just like
118   a normal file.
119
120   .. versionchanged:: 3.3
121      the truncate method now accepts a ``size`` argument.
122
123   .. versionchanged:: 3.8
124      Added *errors* parameter.
125
126   .. versionchanged:: 3.11
127      Fully implements the :class:`io.BufferedIOBase` and
128      :class:`io.TextIOBase` abstract base classes (depending on whether binary
129      or text *mode* was specified).
130
131
132.. class:: TemporaryDirectory(suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False)
133
134   This class securely creates a temporary directory using the same rules as :func:`mkdtemp`.
135   The resulting object can be used as a context manager (see
136   :ref:`tempfile-examples`).  On completion of the context or destruction
137   of the temporary directory object, the newly created temporary directory
138   and all its contents are removed from the filesystem.
139
140   The directory name can be retrieved from the :attr:`name` attribute of the
141   returned object.  When the returned object is used as a context manager, the
142   :attr:`name` will be assigned to the target of the :keyword:`!as` clause in
143   the :keyword:`with` statement, if there is one.
144
145   The directory can be explicitly cleaned up by calling the
146   :func:`cleanup` method. If *ignore_cleanup_errors* is true, any unhandled
147   exceptions during explicit or implicit cleanup (such as a
148   :exc:`PermissionError` removing open files on Windows) will be ignored,
149   and the remaining removable items deleted on a "best-effort" basis.
150   Otherwise, errors will be raised in whatever context cleanup occurs
151   (the :func:`cleanup` call, exiting the context manager, when the object
152   is garbage-collected or during interpreter shutdown).
153
154   .. audit-event:: tempfile.mkdtemp fullpath tempfile.TemporaryDirectory
155
156   .. versionadded:: 3.2
157
158   .. versionchanged:: 3.10
159      Added *ignore_cleanup_errors* parameter.
160
161
162.. function:: mkstemp(suffix=None, prefix=None, dir=None, text=False)
163
164   Creates a temporary file in the most secure manner possible.  There are
165   no race conditions in the file's creation, assuming that the platform
166   properly implements the :const:`os.O_EXCL` flag for :func:`os.open`.  The
167   file is readable and writable only by the creating user ID.  If the
168   platform uses permission bits to indicate whether a file is executable,
169   the file is executable by no one.  The file descriptor is not inherited
170   by child processes.
171
172   Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible
173   for deleting the temporary file when done with it.
174
175   If *suffix* is not ``None``, the file name will end with that suffix,
176   otherwise there will be no suffix.  :func:`mkstemp` does not put a dot
177   between the file name and the suffix; if you need one, put it at the
178   beginning of *suffix*.
179
180   If *prefix* is not ``None``, the file name will begin with that prefix;
181   otherwise, a default prefix is used.  The default is the return value of
182   :func:`gettempprefix` or :func:`gettempprefixb`, as appropriate.
183
184   If *dir* is not ``None``, the file will be created in that directory;
185   otherwise, a default directory is used.  The default directory is chosen
186   from a platform-dependent list, but the user of the application can
187   control the directory location by setting the *TMPDIR*, *TEMP* or *TMP*
188   environment variables.  There is thus no guarantee that the generated
189   filename will have any nice properties, such as not requiring quoting
190   when passed to external commands via ``os.popen()``.
191
192   If any of *suffix*, *prefix*, and *dir* are not
193   ``None``, they must be the same type.
194   If they are bytes, the returned name will be bytes instead of str.
195   If you want to force a bytes return value with otherwise default behavior,
196   pass ``suffix=b''``.
197
198   If *text* is specified and true, the file is opened in text mode.
199   Otherwise, (the default) the file is opened in binary mode.
200
201   :func:`mkstemp` returns a tuple containing an OS-level handle to an open
202   file (as would be returned by :func:`os.open`) and the absolute pathname
203   of that file, in that order.
204
205   .. audit-event:: tempfile.mkstemp fullpath tempfile.mkstemp
206
207   .. versionchanged:: 3.5
208      *suffix*, *prefix*, and *dir* may now be supplied in bytes in order to
209      obtain a bytes return value.  Prior to this, only str was allowed.
210      *suffix* and *prefix* now accept and default to ``None`` to cause
211      an appropriate default value to be used.
212
213   .. versionchanged:: 3.6
214      The *dir* parameter now accepts a :term:`path-like object`.
215
216
217.. function:: mkdtemp(suffix=None, prefix=None, dir=None)
218
219   Creates a temporary directory in the most secure manner possible. There
220   are no race conditions in the directory's creation.  The directory is
221   readable, writable, and searchable only by the creating user ID.
222
223   The user of :func:`mkdtemp` is responsible for deleting the temporary
224   directory and its contents when done with it.
225
226   The *prefix*, *suffix*, and *dir* arguments are the same as for
227   :func:`mkstemp`.
228
229   :func:`mkdtemp` returns the absolute pathname of the new directory if *dir*
230   is ``None`` or is an absolute path. If *dir* is a relative path,
231   :func:`mkdtemp` returns a relative path on Python 3.11 and lower. However,
232   on 3.12 it will return an absolute path in all situations.
233
234   .. audit-event:: tempfile.mkdtemp fullpath tempfile.mkdtemp
235
236   .. versionchanged:: 3.5
237      *suffix*, *prefix*, and *dir* may now be supplied in bytes in order to
238      obtain a bytes return value.  Prior to this, only str was allowed.
239      *suffix* and *prefix* now accept and default to ``None`` to cause
240      an appropriate default value to be used.
241
242   .. versionchanged:: 3.6
243      The *dir* parameter now accepts a :term:`path-like object`.
244
245
246.. function:: gettempdir()
247
248   Return the name of the directory used for temporary files. This
249   defines the default value for the *dir* argument to all functions
250   in this module.
251
252   Python searches a standard list of directories to find one which
253   the calling user can create files in.  The list is:
254
255   #. The directory named by the :envvar:`TMPDIR` environment variable.
256
257   #. The directory named by the :envvar:`TEMP` environment variable.
258
259   #. The directory named by the :envvar:`TMP` environment variable.
260
261   #. A platform-specific location:
262
263      * On Windows, the directories :file:`C:\\TEMP`, :file:`C:\\TMP`,
264        :file:`\\TEMP`, and :file:`\\TMP`, in that order.
265
266      * On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and
267        :file:`/usr/tmp`, in that order.
268
269   #. As a last resort, the current working directory.
270
271   The result of this search is cached, see the description of
272   :data:`tempdir` below.
273
274   .. versionchanged:: 3.10
275
276      Always returns a str.  Previously it would return any :data:`tempdir`
277      value regardless of type so long as it was not ``None``.
278
279.. function:: gettempdirb()
280
281   Same as :func:`gettempdir` but the return value is in bytes.
282
283   .. versionadded:: 3.5
284
285.. function:: gettempprefix()
286
287   Return the filename prefix used to create temporary files.  This does not
288   contain the directory component.
289
290.. function:: gettempprefixb()
291
292   Same as :func:`gettempprefix` but the return value is in bytes.
293
294   .. versionadded:: 3.5
295
296The module uses a global variable to store the name of the directory
297used for temporary files returned by :func:`gettempdir`.  It can be
298set directly to override the selection process, but this is discouraged.
299All functions in this module take a *dir* argument which can be used
300to specify the directory. This is the recommended approach that does
301not surprise other unsuspecting code by changing global API behavior.
302
303.. data:: tempdir
304
305   When set to a value other than ``None``, this variable defines the
306   default value for the *dir* argument to the functions defined in this
307   module, including its type, bytes or str.  It cannot be a
308   :term:`path-like object`.
309
310   If ``tempdir`` is ``None`` (the default) at any call to any of the above
311   functions except :func:`gettempprefix` it is initialized following the
312   algorithm described in :func:`gettempdir`.
313
314   .. note::
315
316      Beware that if you set ``tempdir`` to a bytes value, there is a
317      nasty side effect: The global default return type of
318      :func:`mkstemp` and :func:`mkdtemp` changes to bytes when no
319      explicit ``prefix``, ``suffix``, or ``dir`` arguments of type
320      str are supplied. Please do not write code expecting or
321      depending on this. This awkward behavior is maintained for
322      compatibility with the historical implementation.
323
324.. _tempfile-examples:
325
326Examples
327--------
328
329Here are some examples of typical usage of the :mod:`tempfile` module::
330
331    >>> import tempfile
332
333    # create a temporary file and write some data to it
334    >>> fp = tempfile.TemporaryFile()
335    >>> fp.write(b'Hello world!')
336    # read data from file
337    >>> fp.seek(0)
338    >>> fp.read()
339    b'Hello world!'
340    # close the file, it will be removed
341    >>> fp.close()
342
343    # create a temporary file using a context manager
344    >>> with tempfile.TemporaryFile() as fp:
345    ...     fp.write(b'Hello world!')
346    ...     fp.seek(0)
347    ...     fp.read()
348    b'Hello world!'
349    >>>
350    # file is now closed and removed
351
352    # create a temporary directory using the context manager
353    >>> with tempfile.TemporaryDirectory() as tmpdirname:
354    ...     print('created temporary directory', tmpdirname)
355    >>>
356    # directory and contents have been removed
357
358.. _tempfile-mktemp-deprecated:
359
360Deprecated functions and variables
361----------------------------------
362
363A historical way to create temporary files was to first generate a
364file name with the :func:`mktemp` function and then create a file
365using this name. Unfortunately this is not secure, because a different
366process may create a file with this name in the time between the call
367to :func:`mktemp` and the subsequent attempt to create the file by the
368first process. The solution is to combine the two steps and create the
369file immediately. This approach is used by :func:`mkstemp` and the
370other functions described above.
371
372.. function:: mktemp(suffix='', prefix='tmp', dir=None)
373
374   .. deprecated:: 2.3
375      Use :func:`mkstemp` instead.
376
377   Return an absolute pathname of a file that did not exist at the time the
378   call is made.  The *prefix*, *suffix*, and *dir* arguments are similar
379   to those of :func:`mkstemp`, except that bytes file names, ``suffix=None``
380   and ``prefix=None`` are not supported.
381
382   .. warning::
383
384      Use of this function may introduce a security hole in your program.  By
385      the time you get around to doing anything with the file name it returns,
386      someone else may have beaten you to the punch.  :func:`mktemp` usage can
387      be replaced easily with :func:`NamedTemporaryFile`, passing it the
388      ``delete=False`` parameter::
389
390         >>> f = NamedTemporaryFile(delete=False)
391         >>> f.name
392         '/tmp/tmptjujjt'
393         >>> f.write(b"Hello World!\n")
394         13
395         >>> f.close()
396         >>> os.unlink(f.name)
397         >>> os.path.exists(f.name)
398         False
399