blob: 83f994170a96c4ed0bb3aab8035447e3b86a620c [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`tempfile` --- Generate temporary files and directories
2============================================================
3
4.. sectionauthor:: Zack Weinberg <zack@codesourcery.com>
5
6
7.. module:: tempfile
8 :synopsis: Generate temporary files and directories.
9
10
11.. index::
12 pair: temporary; file name
13 pair: temporary; file
14
Raymond Hettingera1993682011-01-27 01:20:32 +000015**Source code:** :source:`Lib/tempfile.py`
16
17--------------
18
Robert Collins2ebdc132015-08-13 11:38:02 +120019This module creates temporary files and directories. It works on all
20supported platforms. :class:`TemporaryFile`, :class:`NamedTemporaryFile`,
21:class:`TemporaryDirectory`, and :class:`SpooledTemporaryFile` are high-level
22interfaces which provide automatic cleanup and can be used as
23context managers. :func:`mkstemp` and
24:func:`mkdtemp` are lower-level functions which require manual cleanup.
Georg Brandl116aa622007-08-15 14:28:22 +000025
Robert Collins2ebdc132015-08-13 11:38:02 +120026All the user-callable functions and constructors take additional arguments which
27allow direct control over the location and name of temporary files and
28directories. Files names used by this module include a string of
29random characters which allows those files to be securely created in
30shared temporary directories.
Christian Heimes81ee3ef2008-05-04 22:42:01 +000031To maintain backward compatibility, the argument order is somewhat odd; it
32is recommended to use keyword arguments for clarity.
Georg Brandl116aa622007-08-15 14:28:22 +000033
Nick Coghlan543af752010-10-24 11:23:25 +000034The module defines the following user-callable items:
Georg Brandl116aa622007-08-15 14:28:22 +000035
Georg Brandl14dfede2010-05-21 21:12:07 +000036.. function:: TemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None)
Georg Brandl116aa622007-08-15 14:28:22 +000037
Antoine Pitrou11cb9612010-09-15 11:11:28 +000038 Return a :term:`file-like object` that can be used as a temporary storage area.
Robert Collins2ebdc132015-08-13 11:38:02 +120039 The file is created securely, using the same rules as :func:`mkstemp`. It will be destroyed as soon
Georg Brandl116aa622007-08-15 14:28:22 +000040 as it is closed (including an implicit close when the object is garbage
Robert Collins2ebdc132015-08-13 11:38:02 +120041 collected). Under Unix, the directory entry for the file is either not created at all or is removed
Christian Heimes81ee3ef2008-05-04 22:42:01 +000042 immediately after the file is created. Other platforms do not support
43 this; your code should not rely on a temporary file created using this
44 function having or not having a visible name in the file system.
Georg Brandl116aa622007-08-15 14:28:22 +000045
Robert Collins2ebdc132015-08-13 11:38:02 +120046 The resulting object can be used as a context manager (see
47 :ref:`tempfile-examples`). On completion of the context or
48 destruction of the file object the temporary file will be removed
49 from the filesystem.
50
Christian Heimes81ee3ef2008-05-04 22:42:01 +000051 The *mode* parameter defaults to ``'w+b'`` so that the file created can
52 be read and written without being closed. Binary mode is used so that it
53 behaves consistently on all platforms without regard for the data that is
Georg Brandl14dfede2010-05-21 21:12:07 +000054 stored. *buffering*, *encoding* and *newline* are interpreted as for
55 :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +000056
Robert Collins2ebdc132015-08-13 11:38:02 +120057 The *dir*, *prefix* and *suffix* parameters have the same meaning
58 as with :func:`mkstemp`.
Georg Brandl116aa622007-08-15 14:28:22 +000059
Christian Heimes7f044312008-01-06 17:05:40 +000060 The returned object is a true file object on POSIX platforms. On other
Georg Brandl502d9a52009-07-26 15:02:41 +000061 platforms, it is a file-like object whose :attr:`!file` attribute is the
Robert Collins2ebdc132015-08-13 11:38:02 +120062 underlying true file object.
Christian Heimes7f044312008-01-06 17:05:40 +000063
Victor Stinnerd967fc92014-06-05 14:27:45 +020064 The :py:data:`os.O_TMPFILE` flag is used if it is available and works
Robert Collins2ebdc132015-08-13 11:38:02 +120065 (Linux-specific, requires Linux kernel 3.11 or later).
Victor Stinnerd967fc92014-06-05 14:27:45 +020066
67 .. versionchanged:: 3.5
68
69 The :py:data:`os.O_TMPFILE` flag is now used if available.
70
Georg Brandl116aa622007-08-15 14:28:22 +000071
Georg Brandl14dfede2010-05-21 21:12:07 +000072.. function:: NamedTemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None, delete=True)
Georg Brandl116aa622007-08-15 14:28:22 +000073
Christian Heimes81ee3ef2008-05-04 22:42:01 +000074 This function operates exactly as :func:`TemporaryFile` does, except that
75 the file is guaranteed to have a visible name in the file system (on
76 Unix, the directory entry is not unlinked). That name can be retrieved
Senthil Kumarana6bac952011-07-04 11:28:30 -070077 from the :attr:`name` attribute of the file object. Whether the name can be
Christian Heimes81ee3ef2008-05-04 22:42:01 +000078 used to open the file a second time, while the named temporary file is
79 still open, varies across platforms (it can be so used on Unix; it cannot
80 on Windows NT or later). If *delete* is true (the default), the file is
81 deleted as soon as it is closed.
Georg Brandl502d9a52009-07-26 15:02:41 +000082 The returned object is always a file-like object whose :attr:`!file`
Christian Heimes81ee3ef2008-05-04 22:42:01 +000083 attribute is the underlying true file object. This file-like object can
84 be used in a :keyword:`with` statement, just like a normal file.
Georg Brandl116aa622007-08-15 14:28:22 +000085
Georg Brandl116aa622007-08-15 14:28:22 +000086
Georg Brandl14dfede2010-05-21 21:12:07 +000087.. function:: SpooledTemporaryFile(max_size=0, mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None)
Georg Brandl116aa622007-08-15 14:28:22 +000088
Christian Heimes81ee3ef2008-05-04 22:42:01 +000089 This function operates exactly as :func:`TemporaryFile` does, except that
90 data is spooled in memory until the file size exceeds *max_size*, or
91 until the file's :func:`fileno` method is called, at which point the
92 contents are written to disk and operation proceeds as with
93 :func:`TemporaryFile`.
Georg Brandl116aa622007-08-15 14:28:22 +000094
Christian Heimes81ee3ef2008-05-04 22:42:01 +000095 The resulting file has one additional method, :func:`rollover`, which
96 causes the file to roll over to an on-disk file regardless of its size.
Georg Brandl116aa622007-08-15 14:28:22 +000097
Christian Heimes81ee3ef2008-05-04 22:42:01 +000098 The returned object is a file-like object whose :attr:`_file` attribute
Serhiy Storchakae79be872013-08-17 00:09:55 +030099 is either a :class:`io.BytesIO` or :class:`io.StringIO` object (depending on
Serhiy Storchaka4b109cb2013-02-09 11:51:21 +0200100 whether binary or text *mode* was specified) or a true file
Serhiy Storchaka4f169a72013-02-09 11:46:42 +0200101 object, depending on whether :func:`rollover` has been called. This
102 file-like object can be used in a :keyword:`with` statement, just like
103 a normal file.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000104
R David Murrayca76ea12012-10-06 18:32:39 -0400105 .. versionchanged:: 3.3
106 the truncate method now accepts a ``size`` argument.
107
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000108
Nick Coghlan543af752010-10-24 11:23:25 +0000109.. function:: TemporaryDirectory(suffix='', prefix='tmp', dir=None)
110
Robert Collins2ebdc132015-08-13 11:38:02 +1200111 This function securely creates a temporary directory using the same rules as :func:`mkdtemp`.
Nick Coghlan543af752010-10-24 11:23:25 +0000112 The resulting object can be used as a context manager (see
Robert Collins2ebdc132015-08-13 11:38:02 +1200113 :ref:`tempfile-examples`). On completion of the context or destruction
R David Murray23686072014-02-05 14:53:40 -0500114 of the temporary directory object the newly created temporary directory
Nick Coghlan543af752010-10-24 11:23:25 +0000115 and all its contents are removed from the filesystem.
116
R David Murray23686072014-02-05 14:53:40 -0500117 The directory name can be retrieved from the :attr:`name` attribute of the
118 returned object. When the returned object is used as a context manager, the
119 :attr:`name` will be assigned to the target of the :keyword:`as` clause in
120 the :keyword:`with` statement, if there is one.
Nick Coghlan543af752010-10-24 11:23:25 +0000121
122 The directory can be explicitly cleaned up by calling the
123 :func:`cleanup` method.
124
125 .. versionadded:: 3.2
126
127
Gregory P. Smithad577b92015-05-22 16:18:14 -0700128.. function:: mkstemp(suffix=None, prefix=None, dir=None, text=False)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000129
130 Creates a temporary file in the most secure manner possible. There are
131 no race conditions in the file's creation, assuming that the platform
132 properly implements the :const:`os.O_EXCL` flag for :func:`os.open`. The
133 file is readable and writable only by the creating user ID. If the
134 platform uses permission bits to indicate whether a file is executable,
135 the file is executable by no one. The file descriptor is not inherited
136 by child processes.
137
138 Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible
139 for deleting the temporary file when done with it.
140
141 If *suffix* is specified, the file name will end with that suffix,
142 otherwise there will be no suffix. :func:`mkstemp` does not put a dot
143 between the file name and the suffix; if you need one, put it at the
144 beginning of *suffix*.
145
146 If *prefix* is specified, the file name will begin with that prefix;
147 otherwise, a default prefix is used.
148
149 If *dir* is specified, the file will be created in that directory;
150 otherwise, a default directory is used. The default directory is chosen
151 from a platform-dependent list, but the user of the application can
152 control the directory location by setting the *TMPDIR*, *TEMP* or *TMP*
153 environment variables. There is thus no guarantee that the generated
154 filename will have any nice properties, such as not requiring quoting
155 when passed to external commands via ``os.popen()``.
156
Gregory P. Smithad577b92015-05-22 16:18:14 -0700157 *suffix*, *prefix*, and *dir* must all contain the same type, if specified.
158 If they are bytes, the returned name will be bytes instead of str.
159 If you want to force a bytes return value with otherwise default behavior,
160 pass ``suffix=b''``.
161
162 A *prefix* value of ``None`` means use the return value of
163 :func:`gettempprefix` or :func:`gettempprefixb` as appropriate.
164
165 A *suffix* value of ``None`` means use an appropriate empty value.
166
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000167 If *text* is specified, it indicates whether to open the file in binary
168 mode (the default) or text mode. On some platforms, this makes no
169 difference.
170
171 :func:`mkstemp` returns a tuple containing an OS-level handle to an open
172 file (as would be returned by :func:`os.open`) and the absolute pathname
173 of that file, in that order.
174
Gregory P. Smithad577b92015-05-22 16:18:14 -0700175 .. versionchanged:: 3.5
176 *suffix*, *prefix*, and *dir* may now be supplied in bytes in order to
177 obtain a bytes return value. Prior to this, only str was allowed.
178 *suffix* and *prefix* now accept and default to ``None`` to cause
179 an appropriate default value to be used.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000180
Gregory P. Smithad577b92015-05-22 16:18:14 -0700181
182.. function:: mkdtemp(suffix=None, prefix=None, dir=None)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000183
184 Creates a temporary directory in the most secure manner possible. There
185 are no race conditions in the directory's creation. The directory is
186 readable, writable, and searchable only by the creating user ID.
187
188 The user of :func:`mkdtemp` is responsible for deleting the temporary
189 directory and its contents when done with it.
190
191 The *prefix*, *suffix*, and *dir* arguments are the same as for
192 :func:`mkstemp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
194 :func:`mkdtemp` returns the absolute pathname of the new directory.
195
Gregory P. Smithad577b92015-05-22 16:18:14 -0700196 .. versionchanged:: 3.5
197 *suffix*, *prefix*, and *dir* may now be supplied in bytes in order to
198 obtain a bytes return value. Prior to this, only str was allowed.
199 *suffix* and *prefix* now accept and default to ``None`` to cause
200 an appropriate default value to be used.
201
Georg Brandl116aa622007-08-15 14:28:22 +0000202
Robert Collins2ebdc132015-08-13 11:38:02 +1200203.. function:: gettempdir()
Georg Brandl116aa622007-08-15 14:28:22 +0000204
Robert Collins2ebdc132015-08-13 11:38:02 +1200205 Return the name of the directory used for temporary files. This
206 defines the default value for the *dir* argument to all functions
207 in this module.
Georg Brandl116aa622007-08-15 14:28:22 +0000208
Robert Collins2ebdc132015-08-13 11:38:02 +1200209 Python searches a standard list of directories to find one which
210 the calling user can create files in. The list is:
Georg Brandl116aa622007-08-15 14:28:22 +0000211
212 #. The directory named by the :envvar:`TMPDIR` environment variable.
213
214 #. The directory named by the :envvar:`TEMP` environment variable.
215
216 #. The directory named by the :envvar:`TMP` environment variable.
217
218 #. A platform-specific location:
219
Georg Brandl116aa622007-08-15 14:28:22 +0000220 * On Windows, the directories :file:`C:\\TEMP`, :file:`C:\\TMP`,
221 :file:`\\TEMP`, and :file:`\\TMP`, in that order.
222
223 * On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and
224 :file:`/usr/tmp`, in that order.
225
226 #. As a last resort, the current working directory.
227
Robert Collins2ebdc132015-08-13 11:38:02 +1200228 The result of this search is cached, see the description of
229 :data:`tempdir` below.
Georg Brandl116aa622007-08-15 14:28:22 +0000230
Gregory P. Smithad577b92015-05-22 16:18:14 -0700231.. function:: gettempdirb()
232
233 Same as :func:`gettempdir` but the return value is in bytes.
234
235 .. versionadded:: 3.5
Georg Brandl116aa622007-08-15 14:28:22 +0000236
Georg Brandl116aa622007-08-15 14:28:22 +0000237.. function:: gettempprefix()
238
239 Return the filename prefix used to create temporary files. This does not
Georg Brandl4b26ff82008-08-04 07:24:52 +0000240 contain the directory component.
Georg Brandl116aa622007-08-15 14:28:22 +0000241
Gregory P. Smithad577b92015-05-22 16:18:14 -0700242.. function:: gettempprefixb()
243
244 Same as :func:`gettempprefixb` but the return value is in bytes.
245
246 .. versionadded:: 3.5
247
Robert Collins2ebdc132015-08-13 11:38:02 +1200248The module uses a global variable to store the name of the directory
249used for temporary files returned by :func:`gettempdir`. It can be
250set directly to override the selection process, but this is discouraged.
251All functions in this module take a *dir* argument which can be used
252to specify the directory and this is the recommend approach.
253
254.. data:: tempdir
255
256 When set to a value other than ``None``, this variable defines the
257 default value for the *dir* argument to all the functions defined in this
258 module.
259
260 If ``tempdir`` is unset or ``None`` at any call to any of the above
261 functions except :func:`gettempprefix` it is initalized following the
262 algorithm described in :func:`gettempdir`.
263
264.. _tempfile-examples:
Nick Coghlan543af752010-10-24 11:23:25 +0000265
266Examples
267--------
268
269Here are some examples of typical usage of the :mod:`tempfile` module::
270
271 >>> import tempfile
272
273 # create a temporary file and write some data to it
274 >>> fp = tempfile.TemporaryFile()
Ross Lagerwall810b94a2011-04-10 09:30:04 +0200275 >>> fp.write(b'Hello world!')
Nick Coghlan543af752010-10-24 11:23:25 +0000276 # read data from file
277 >>> fp.seek(0)
278 >>> fp.read()
Ross Lagerwall810b94a2011-04-10 09:30:04 +0200279 b'Hello world!'
Nick Coghlan543af752010-10-24 11:23:25 +0000280 # close the file, it will be removed
281 >>> fp.close()
282
283 # create a temporary file using a context manager
284 >>> with tempfile.TemporaryFile() as fp:
Ross Lagerwall810b94a2011-04-10 09:30:04 +0200285 ... fp.write(b'Hello world!')
Nick Coghlan543af752010-10-24 11:23:25 +0000286 ... fp.seek(0)
287 ... fp.read()
Ross Lagerwall810b94a2011-04-10 09:30:04 +0200288 b'Hello world!'
Nick Coghlan543af752010-10-24 11:23:25 +0000289 >>>
290 # file is now closed and removed
291
292 # create a temporary directory using the context manager
293 >>> with tempfile.TemporaryDirectory() as tmpdirname:
Ross Lagerwall810b94a2011-04-10 09:30:04 +0200294 ... print('created temporary directory', tmpdirname)
Nick Coghlan543af752010-10-24 11:23:25 +0000295 >>>
296 # directory and contents have been removed
297
Robert Collins2ebdc132015-08-13 11:38:02 +1200298
299Deprecated functions and variables
300----------------------------------
301
302A historical way to create temporary files was to first generate a
303file name with the :func:`mktemp` function and then create a file
304using this name. Unfortunately this is not secure, because a different
305process may create a file with this name in the time between the call
306to :func:`mktemp` and the subsequent attempt to create the file by the
307first process. The solution is to combine the two steps and create the
308file immediately. This approach is used by :func:`mkstemp` and the
309other functions described above.
310
311.. function:: mktemp(suffix='', prefix='tmp', dir=None)
312
313 .. deprecated:: 2.3
314 Use :func:`mkstemp` instead.
315
316 Return an absolute pathname of a file that did not exist at the time the
317 call is made. The *prefix*, *suffix*, and *dir* arguments are the same
318 as for :func:`mkstemp`.
319
320 .. warning::
321
322 Use of this function may introduce a security hole in your program. By
323 the time you get around to doing anything with the file name it returns,
324 someone else may have beaten you to the punch. :func:`mktemp` usage can
325 be replaced easily with :func:`NamedTemporaryFile`, passing it the
326 ``delete=False`` parameter::
327
328 >>> f = NamedTemporaryFile(delete=False)
329 >>> f.name
330 '/tmp/tmptjujjt'
331 >>> f.write(b"Hello World!\n")
332 13
333 >>> f.close()
334 >>> os.unlink(f.name)
335 >>> os.path.exists(f.name)
336 False