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 <zack@codesourcery.com> 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=None, 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 .. audit-event:: tempfile.mkstemp fullpath tempfile.TemporaryFile 66 67 .. versionchanged:: 3.5 68 69 The :py:data:`os.O_TMPFILE` flag is now used if available. 70 71 .. versionchanged:: 3.8 72 Added *errors* parameter. 73 74 75.. function:: NamedTemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None) 76 77 This function operates exactly as :func:`TemporaryFile` does, except that 78 the file is guaranteed to have a visible name in the file system (on 79 Unix, the directory entry is not unlinked). That name can be retrieved 80 from the :attr:`name` attribute of the returned 81 file-like object. Whether the name can be 82 used to open the file a second time, while the named temporary file is 83 still open, varies across platforms (it can be so used on Unix; it cannot 84 on Windows NT or later). If *delete* is true (the default), the file is 85 deleted as soon as it is closed. 86 The returned object is always a file-like object whose :attr:`!file` 87 attribute is the underlying true file object. This file-like object can 88 be used in a :keyword:`with` statement, just like a normal file. 89 90 .. audit-event:: tempfile.mkstemp fullpath tempfile.NamedTemporaryFile 91 92 .. versionchanged:: 3.8 93 Added *errors* parameter. 94 95 96.. function:: SpooledTemporaryFile(max_size=0, mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None) 97 98 This function operates exactly as :func:`TemporaryFile` does, except that 99 data is spooled in memory until the file size exceeds *max_size*, or 100 until the file's :func:`fileno` method is called, at which point the 101 contents are written to disk and operation proceeds as with 102 :func:`TemporaryFile`. 103 104 The resulting file has one additional method, :func:`rollover`, which 105 causes the file to roll over to an on-disk file regardless of its size. 106 107 The returned object is a file-like object whose :attr:`_file` attribute 108 is either an :class:`io.BytesIO` or :class:`io.TextIOWrapper` object 109 (depending on whether binary or text *mode* was specified) or a true file 110 object, depending on whether :func:`rollover` has been called. This 111 file-like object can be used in a :keyword:`with` statement, just like 112 a normal file. 113 114 .. versionchanged:: 3.3 115 the truncate method now accepts a ``size`` argument. 116 117 .. versionchanged:: 3.8 118 Added *errors* parameter. 119 120 121.. function:: TemporaryDirectory(suffix=None, prefix=None, dir=None) 122 123 This function securely creates a temporary directory using the same rules as :func:`mkdtemp`. 124 The resulting object can be used as a context manager (see 125 :ref:`tempfile-examples`). On completion of the context or destruction 126 of the temporary directory object the newly created temporary directory 127 and all its contents are removed from the filesystem. 128 129 The directory name can be retrieved from the :attr:`name` attribute of the 130 returned object. When the returned object is used as a context manager, the 131 :attr:`name` will be assigned to the target of the :keyword:`!as` clause in 132 the :keyword:`with` statement, if there is one. 133 134 The directory can be explicitly cleaned up by calling the 135 :func:`cleanup` method. 136 137 .. audit-event:: tempfile.mkdtemp fullpath tempfile.TemporaryDirectory 138 139 .. versionadded:: 3.2 140 141 142.. function:: mkstemp(suffix=None, prefix=None, dir=None, text=False) 143 144 Creates a temporary file in the most secure manner possible. There are 145 no race conditions in the file's creation, assuming that the platform 146 properly implements the :const:`os.O_EXCL` flag for :func:`os.open`. The 147 file is readable and writable only by the creating user ID. If the 148 platform uses permission bits to indicate whether a file is executable, 149 the file is executable by no one. The file descriptor is not inherited 150 by child processes. 151 152 Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible 153 for deleting the temporary file when done with it. 154 155 If *suffix* is not ``None``, the file name will end with that suffix, 156 otherwise there will be no suffix. :func:`mkstemp` does not put a dot 157 between the file name and the suffix; if you need one, put it at the 158 beginning of *suffix*. 159 160 If *prefix* is not ``None``, the file name will begin with that prefix; 161 otherwise, a default prefix is used. The default is the return value of 162 :func:`gettempprefix` or :func:`gettempprefixb`, as appropriate. 163 164 If *dir* is not ``None``, the file will be created in that directory; 165 otherwise, a default directory is used. The default directory is chosen 166 from a platform-dependent list, but the user of the application can 167 control the directory location by setting the *TMPDIR*, *TEMP* or *TMP* 168 environment variables. There is thus no guarantee that the generated 169 filename will have any nice properties, such as not requiring quoting 170 when passed to external commands via ``os.popen()``. 171 172 If any of *suffix*, *prefix*, and *dir* are not 173 ``None``, they must be the same type. 174 If they are bytes, the returned name will be bytes instead of str. 175 If you want to force a bytes return value with otherwise default behavior, 176 pass ``suffix=b''``. 177 178 If *text* is specified, it indicates whether to open the file in binary 179 mode (the default) or text mode. On some platforms, this makes no 180 difference. 181 182 :func:`mkstemp` returns a tuple containing an OS-level handle to an open 183 file (as would be returned by :func:`os.open`) and the absolute pathname 184 of that file, in that order. 185 186 .. audit-event:: tempfile.mkstemp fullpath tempfile.mkstemp 187 188 .. versionchanged:: 3.5 189 *suffix*, *prefix*, and *dir* may now be supplied in bytes in order to 190 obtain a bytes return value. Prior to this, only str was allowed. 191 *suffix* and *prefix* now accept and default to ``None`` to cause 192 an appropriate default value to be used. 193 194 .. versionchanged:: 3.6 195 The *dir* parameter now accepts a :term:`path-like object`. 196 197 198.. function:: mkdtemp(suffix=None, prefix=None, dir=None) 199 200 Creates a temporary directory in the most secure manner possible. There 201 are no race conditions in the directory's creation. The directory is 202 readable, writable, and searchable only by the creating user ID. 203 204 The user of :func:`mkdtemp` is responsible for deleting the temporary 205 directory and its contents when done with it. 206 207 The *prefix*, *suffix*, and *dir* arguments are the same as for 208 :func:`mkstemp`. 209 210 :func:`mkdtemp` returns the absolute pathname of the new directory. 211 212 .. audit-event:: tempfile.mkdtemp fullpath tempfile.mkdtemp 213 214 .. versionchanged:: 3.5 215 *suffix*, *prefix*, and *dir* may now be supplied in bytes in order to 216 obtain a bytes return value. Prior to this, only str was allowed. 217 *suffix* and *prefix* now accept and default to ``None`` to cause 218 an appropriate default value to be used. 219 220 .. versionchanged:: 3.6 221 The *dir* parameter now accepts a :term:`path-like object`. 222 223 224.. function:: gettempdir() 225 226 Return the name of the directory used for temporary files. This 227 defines the default value for the *dir* argument to all functions 228 in this module. 229 230 Python searches a standard list of directories to find one which 231 the calling user can create files in. The list is: 232 233 #. The directory named by the :envvar:`TMPDIR` environment variable. 234 235 #. The directory named by the :envvar:`TEMP` environment variable. 236 237 #. The directory named by the :envvar:`TMP` environment variable. 238 239 #. A platform-specific location: 240 241 * On Windows, the directories :file:`C:\\TEMP`, :file:`C:\\TMP`, 242 :file:`\\TEMP`, and :file:`\\TMP`, in that order. 243 244 * On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and 245 :file:`/usr/tmp`, in that order. 246 247 #. As a last resort, the current working directory. 248 249 The result of this search is cached, see the description of 250 :data:`tempdir` below. 251 252.. function:: gettempdirb() 253 254 Same as :func:`gettempdir` but the return value is in bytes. 255 256 .. versionadded:: 3.5 257 258.. function:: gettempprefix() 259 260 Return the filename prefix used to create temporary files. This does not 261 contain the directory component. 262 263.. function:: gettempprefixb() 264 265 Same as :func:`gettempprefix` but the return value is in bytes. 266 267 .. versionadded:: 3.5 268 269The module uses a global variable to store the name of the directory 270used for temporary files returned by :func:`gettempdir`. It can be 271set directly to override the selection process, but this is discouraged. 272All functions in this module take a *dir* argument which can be used 273to specify the directory and this is the recommended approach. 274 275.. data:: tempdir 276 277 When set to a value other than ``None``, this variable defines the 278 default value for the *dir* argument to the functions defined in this 279 module. 280 281 If ``tempdir`` is ``None`` (the default) at any call to any of the above 282 functions except :func:`gettempprefix` it is initialized following the 283 algorithm described in :func:`gettempdir`. 284 285.. _tempfile-examples: 286 287Examples 288-------- 289 290Here are some examples of typical usage of the :mod:`tempfile` module:: 291 292 >>> import tempfile 293 294 # create a temporary file and write some data to it 295 >>> fp = tempfile.TemporaryFile() 296 >>> fp.write(b'Hello world!') 297 # read data from file 298 >>> fp.seek(0) 299 >>> fp.read() 300 b'Hello world!' 301 # close the file, it will be removed 302 >>> fp.close() 303 304 # create a temporary file using a context manager 305 >>> with tempfile.TemporaryFile() as fp: 306 ... fp.write(b'Hello world!') 307 ... fp.seek(0) 308 ... fp.read() 309 b'Hello world!' 310 >>> 311 # file is now closed and removed 312 313 # create a temporary directory using the context manager 314 >>> with tempfile.TemporaryDirectory() as tmpdirname: 315 ... print('created temporary directory', tmpdirname) 316 >>> 317 # directory and contents have been removed 318 319 320Deprecated functions and variables 321---------------------------------- 322 323A historical way to create temporary files was to first generate a 324file name with the :func:`mktemp` function and then create a file 325using this name. Unfortunately this is not secure, because a different 326process may create a file with this name in the time between the call 327to :func:`mktemp` and the subsequent attempt to create the file by the 328first process. The solution is to combine the two steps and create the 329file immediately. This approach is used by :func:`mkstemp` and the 330other functions described above. 331 332.. function:: mktemp(suffix='', prefix='tmp', dir=None) 333 334 .. deprecated:: 2.3 335 Use :func:`mkstemp` instead. 336 337 Return an absolute pathname of a file that did not exist at the time the 338 call is made. The *prefix*, *suffix*, and *dir* arguments are similar 339 to those of :func:`mkstemp`, except that bytes file names, ``suffix=None`` 340 and ``prefix=None`` are not supported. 341 342 .. warning:: 343 344 Use of this function may introduce a security hole in your program. By 345 the time you get around to doing anything with the file name it returns, 346 someone else may have beaten you to the punch. :func:`mktemp` usage can 347 be replaced easily with :func:`NamedTemporaryFile`, passing it the 348 ``delete=False`` parameter:: 349 350 >>> f = NamedTemporaryFile(delete=False) 351 >>> f.name 352 '/tmp/tmptjujjt' 353 >>> f.write(b"Hello World!\n") 354 13 355 >>> f.close() 356 >>> os.unlink(f.name) 357 >>> os.path.exists(f.name) 358 False 359