blob: fa0a27f518f7745fd42fbe428af9c7da5907760a [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Éric Araujo29a0b572011-08-19 02:14:03 +020015**Source code:** :source:`Lib/tempfile.py`
16
17--------------
18
Georg Brandl8ec7f652007-08-15 14:28:01 +000019This module generates temporary files and directories. It works on all
20supported platforms.
21
22In version 2.3 of Python, this module was overhauled for enhanced security. It
23now provides three new functions, :func:`NamedTemporaryFile`, :func:`mkstemp`,
24and :func:`mkdtemp`, which should eliminate all remaining need to use the
25insecure :func:`mktemp` function. Temporary file names created by this module
26no longer contain the process ID; instead a string of six random characters is
27used.
28
Skip Montanaro79809922008-04-27 22:52:02 +000029Also, all the user-callable functions now take additional arguments which
30allow direct control over the location and name of temporary files. It is
31no longer necessary to use the global *tempdir* and *template* variables.
32To maintain backward compatibility, the argument order is somewhat odd; it
33is recommended to use keyword arguments for clarity.
Georg Brandl8ec7f652007-08-15 14:28:01 +000034
35The module defines the following user-callable functions:
36
37
Skip Montanaro79809922008-04-27 22:52:02 +000038.. function:: TemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000039
Skip Montanaro79809922008-04-27 22:52:02 +000040 Return a file-like object that can be used as a temporary storage area.
41 The file is created using :func:`mkstemp`. It will be destroyed as soon
Georg Brandl8ec7f652007-08-15 14:28:01 +000042 as it is closed (including an implicit close when the object is garbage
Skip Montanaro79809922008-04-27 22:52:02 +000043 collected). Under Unix, the directory entry for the file is removed
44 immediately after the file is created. Other platforms do not support
45 this; your code should not rely on a temporary file created using this
46 function having or not having a visible name in the file system.
Georg Brandl8ec7f652007-08-15 14:28:01 +000047
Skip Montanaro79809922008-04-27 22:52:02 +000048 The *mode* parameter defaults to ``'w+b'`` so that the file created can
49 be read and written without being closed. Binary mode is used so that it
50 behaves consistently on all platforms without regard for the data that is
51 stored. *bufsize* defaults to ``-1``, meaning that the operating system
52 default is used.
Georg Brandl8ec7f652007-08-15 14:28:01 +000053
54 The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`.
55
Georg Brandlc4768a42008-01-06 15:55:26 +000056 The returned object is a true file object on POSIX platforms. On other
Georg Brandl9fa61bb2009-07-26 14:19:57 +000057 platforms, it is a file-like object whose :attr:`!file` attribute is the
Skip Montanaro79809922008-04-27 22:52:02 +000058 underlying true file object. This file-like object can be used in a
59 :keyword:`with` statement, just like a normal file.
Georg Brandlc4768a42008-01-06 15:55:26 +000060
Georg Brandl8ec7f652007-08-15 14:28:01 +000061
Skip Montanaro79809922008-04-27 22:52:02 +000062.. function:: NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000063
Skip Montanaro79809922008-04-27 22:52:02 +000064 This function operates exactly as :func:`TemporaryFile` does, except that
65 the file is guaranteed to have a visible name in the file system (on
66 Unix, the directory entry is not unlinked). That name can be retrieved
Martin Panterbe9ddc12016-02-22 10:10:00 +000067 from the :attr:`name` attribute of the returned
68 file-like object. Whether the name can be
Skip Montanaro79809922008-04-27 22:52:02 +000069 used to open the file a second time, while the named temporary file is
70 still open, varies across platforms (it can be so used on Unix; it cannot
71 on Windows NT or later). If *delete* is true (the default), the file is
72 deleted as soon as it is closed.
Georg Brandl8ec7f652007-08-15 14:28:01 +000073
Georg Brandl9fa61bb2009-07-26 14:19:57 +000074 The returned object is always a file-like object whose :attr:`!file`
Skip Montanaro79809922008-04-27 22:52:02 +000075 attribute is the underlying true file object. This file-like object can
76 be used in a :keyword:`with` statement, just like a normal file.
Georg Brandlc4768a42008-01-06 15:55:26 +000077
Georg Brandl8ec7f652007-08-15 14:28:01 +000078 .. versionadded:: 2.3
79
80 .. versionadded:: 2.6
81 The *delete* parameter.
82
83
Skip Montanaro79809922008-04-27 22:52:02 +000084.. function:: SpooledTemporaryFile([max_size=0, [mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000085
Skip Montanaro79809922008-04-27 22:52:02 +000086 This function operates exactly as :func:`TemporaryFile` does, except that
87 data is spooled in memory until the file size exceeds *max_size*, or
88 until the file's :func:`fileno` method is called, at which point the
89 contents are written to disk and operation proceeds as with
R David Murrayfefd3ac2012-10-06 18:26:40 -040090 :func:`TemporaryFile`. Also, it's ``truncate`` method does not
91 accept a ``size`` argument.
Georg Brandl8ec7f652007-08-15 14:28:01 +000092
Skip Montanaro79809922008-04-27 22:52:02 +000093 The resulting file has one additional method, :func:`rollover`, which
94 causes the file to roll over to an on-disk file regardless of its size.
Georg Brandl8ec7f652007-08-15 14:28:01 +000095
Georg Brandlc4768a42008-01-06 15:55:26 +000096 The returned object is a file-like object whose :attr:`_file` attribute
Serhiy Storchaka6d5bd522013-08-29 11:44:44 +030097 is either a :class:`~StringIO.StringIO` object or a true file object, depending on
Skip Montanaro79809922008-04-27 22:52:02 +000098 whether :func:`rollover` has been called. This file-like object can be
99 used in a :keyword:`with` statement, just like a normal file.
Georg Brandlc4768a42008-01-06 15:55:26 +0000100
Georg Brandl8ec7f652007-08-15 14:28:01 +0000101 .. versionadded:: 2.6
102
103
Skip Montanaro79809922008-04-27 22:52:02 +0000104.. function:: mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000105
Skip Montanaro79809922008-04-27 22:52:02 +0000106 Creates a temporary file in the most secure manner possible. There are
107 no race conditions in the file's creation, assuming that the platform
108 properly implements the :const:`os.O_EXCL` flag for :func:`os.open`. The
109 file is readable and writable only by the creating user ID. If the
110 platform uses permission bits to indicate whether a file is executable,
111 the file is executable by no one. The file descriptor is not inherited
112 by child processes.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000113
Skip Montanaro79809922008-04-27 22:52:02 +0000114 Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible
115 for deleting the temporary file when done with it.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000116
Skip Montanaro79809922008-04-27 22:52:02 +0000117 If *suffix* is specified, the file name will end with that suffix,
118 otherwise there will be no suffix. :func:`mkstemp` does not put a dot
119 between the file name and the suffix; if you need one, put it at the
120 beginning of *suffix*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000121
Skip Montanaro79809922008-04-27 22:52:02 +0000122 If *prefix* is specified, the file name will begin with that prefix;
123 otherwise, a default prefix is used.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000124
Skip Montanaro79809922008-04-27 22:52:02 +0000125 If *dir* is specified, the file will be created in that directory;
126 otherwise, a default directory is used. The default directory is chosen
127 from a platform-dependent list, but the user of the application can
128 control the directory location by setting the *TMPDIR*, *TEMP* or *TMP*
129 environment variables. There is thus no guarantee that the generated
130 filename will have any nice properties, such as not requiring quoting
131 when passed to external commands via ``os.popen()``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000132
Skip Montanaro79809922008-04-27 22:52:02 +0000133 If *text* is specified, it indicates whether to open the file in binary
134 mode (the default) or text mode. On some platforms, this makes no
135 difference.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000136
Skip Montanaro79809922008-04-27 22:52:02 +0000137 :func:`mkstemp` returns a tuple containing an OS-level handle to an open
138 file (as would be returned by :func:`os.open`) and the absolute pathname
139 of that file, in that order.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000140
141 .. versionadded:: 2.3
142
143
Skip Montanaro79809922008-04-27 22:52:02 +0000144.. function:: mkdtemp([suffix=''[, prefix='tmp'[, dir=None]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000145
Skip Montanaro79809922008-04-27 22:52:02 +0000146 Creates a temporary directory in the most secure manner possible. There
147 are no race conditions in the directory's creation. The directory is
148 readable, writable, and searchable only by the creating user ID.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149
Skip Montanaro79809922008-04-27 22:52:02 +0000150 The user of :func:`mkdtemp` is responsible for deleting the temporary
151 directory and its contents when done with it.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000152
Skip Montanaro79809922008-04-27 22:52:02 +0000153 The *prefix*, *suffix*, and *dir* arguments are the same as for
154 :func:`mkstemp`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000155
156 :func:`mkdtemp` returns the absolute pathname of the new directory.
157
158 .. versionadded:: 2.3
159
160
Skip Montanaro79809922008-04-27 22:52:02 +0000161.. function:: mktemp([suffix=''[, prefix='tmp'[, dir=None]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000162
163 .. deprecated:: 2.3
164 Use :func:`mkstemp` instead.
165
Skip Montanaro79809922008-04-27 22:52:02 +0000166 Return an absolute pathname of a file that did not exist at the time the
167 call is made. The *prefix*, *suffix*, and *dir* arguments are the same
168 as for :func:`mkstemp`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000169
170 .. warning::
171
Georg Brandle92818f2009-01-03 20:47:01 +0000172 Use of this function may introduce a security hole in your program. By
173 the time you get around to doing anything with the file name it returns,
174 someone else may have beaten you to the punch. :func:`mktemp` usage can
175 be replaced easily with :func:`NamedTemporaryFile`, passing it the
176 ``delete=False`` parameter::
Skip Montanaroe404a122008-05-09 00:45:00 +0000177
Benjamin Petersond03238a2008-05-09 00:50:40 +0000178 >>> f = NamedTemporaryFile(delete=False)
Benjamin Petersond03238a2008-05-09 00:50:40 +0000179 >>> f
180 <open file '<fdopen>', mode 'w+b' at 0x384698>
181 >>> f.name
182 '/var/folders/5q/5qTPn6xq2RaWqk+1Ytw3-U+++TI/-Tmp-/tmpG7V1Y0'
183 >>> f.write("Hello World!\n")
184 >>> f.close()
185 >>> os.unlink(f.name)
186 >>> os.path.exists(f.name)
187 False
Georg Brandl8ec7f652007-08-15 14:28:01 +0000188
Georg Brandl50038012014-10-31 10:25:48 +0100189The module uses a global variable that tell it how to construct a
Skip Montanaro79809922008-04-27 22:52:02 +0000190temporary name. They are initialized at the first call to any of the
191functions above. The caller may change them, but this is discouraged; use
192the appropriate function arguments, instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193
194
195.. data:: tempdir
196
Skip Montanaro79809922008-04-27 22:52:02 +0000197 When set to a value other than ``None``, this variable defines the
198 default value for the *dir* argument to all the functions defined in this
199 module.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000200
Skip Montanaro79809922008-04-27 22:52:02 +0000201 If ``tempdir`` is unset or ``None`` at any call to any of the above
202 functions, Python searches a standard list of directories and sets
203 *tempdir* to the first one which the calling user can create files in.
204 The list is:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000205
206 #. The directory named by the :envvar:`TMPDIR` environment variable.
207
208 #. The directory named by the :envvar:`TEMP` environment variable.
209
210 #. The directory named by the :envvar:`TMP` environment variable.
211
212 #. A platform-specific location:
213
214 * On RiscOS, the directory named by the :envvar:`Wimp$ScrapDir` environment
215 variable.
216
217 * On Windows, the directories :file:`C:\\TEMP`, :file:`C:\\TMP`,
218 :file:`\\TEMP`, and :file:`\\TMP`, in that order.
219
220 * On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and
221 :file:`/usr/tmp`, in that order.
222
223 #. As a last resort, the current working directory.
224
225
226.. function:: gettempdir()
227
228 Return the directory currently selected to create temporary files in. If
229 :data:`tempdir` is not ``None``, this simply returns its contents; otherwise,
230 the search described above is performed, and the result returned.
231
Benjamin Petersonb06b4c32008-10-29 20:33:00 +0000232 .. versionadded:: 2.3
233
Georg Brandl8ec7f652007-08-15 14:28:01 +0000234
235.. data:: template
236
237 .. deprecated:: 2.0
238 Use :func:`gettempprefix` instead.
239
240 When set to a value other than ``None``, this variable defines the prefix of the
241 final component of the filenames returned by :func:`mktemp`. A string of six
242 random letters and digits is appended to the prefix to make the filename unique.
Georg Brandl40df8ec2008-08-04 07:23:29 +0000243 The default prefix is :file:`tmp`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244
245 Older versions of this module used to require that ``template`` be set to
246 ``None`` after a call to :func:`os.fork`; this has not been necessary since
247 version 1.5.2.
248
249
250.. function:: gettempprefix()
251
252 Return the filename prefix used to create temporary files. This does not
253 contain the directory component. Using this function is preferred over reading
254 the *template* variable directly.
255
256 .. versionadded:: 1.5.2
257