blob: 96ead1fb89dc22b929ac257641f169f8847846ef [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
Georg Brandl116aa622007-08-15 14:28:22 +000019This module generates temporary files and directories. It works on all
Georg Brandle6bcc912008-05-12 18:05:20 +000020supported platforms. It provides three new functions,
21:func:`NamedTemporaryFile`, :func:`mkstemp`, and :func:`mkdtemp`, which should
22eliminate all remaining need to use the insecure :func:`mktemp` function.
23Temporary file names created by this module no longer contain the process ID;
24instead a string of six random characters is used.
Georg Brandl116aa622007-08-15 14:28:22 +000025
Christian Heimes81ee3ef2008-05-04 22:42:01 +000026Also, all the user-callable functions now take additional arguments which
27allow direct control over the location and name of temporary files. It is
R David Murray3a420c72011-06-22 21:01:13 -040028no longer necessary to use the global *tempdir* variable.
Christian Heimes81ee3ef2008-05-04 22:42:01 +000029To maintain backward compatibility, the argument order is somewhat odd; it
30is recommended to use keyword arguments for clarity.
Georg Brandl116aa622007-08-15 14:28:22 +000031
Nick Coghlan543af752010-10-24 11:23:25 +000032The module defines the following user-callable items:
Georg Brandl116aa622007-08-15 14:28:22 +000033
Georg Brandl14dfede2010-05-21 21:12:07 +000034.. function:: TemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None)
Georg Brandl116aa622007-08-15 14:28:22 +000035
Antoine Pitrou11cb9612010-09-15 11:11:28 +000036 Return a :term:`file-like object` that can be used as a temporary storage area.
Christian Heimes81ee3ef2008-05-04 22:42:01 +000037 The file is created using :func:`mkstemp`. It will be destroyed as soon
Georg Brandl116aa622007-08-15 14:28:22 +000038 as it is closed (including an implicit close when the object is garbage
Christian Heimes81ee3ef2008-05-04 22:42:01 +000039 collected). Under Unix, the directory entry for the file 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.
Georg Brandl116aa622007-08-15 14:28:22 +000043
Christian Heimes81ee3ef2008-05-04 22:42:01 +000044 The *mode* parameter defaults to ``'w+b'`` so that the file created can
45 be read and written without being closed. Binary mode is used so that it
46 behaves consistently on all platforms without regard for the data that is
Georg Brandl14dfede2010-05-21 21:12:07 +000047 stored. *buffering*, *encoding* and *newline* are interpreted as for
48 :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +000049
50 The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`.
51
Christian Heimes7f044312008-01-06 17:05:40 +000052 The returned object is a true file object on POSIX platforms. On other
Georg Brandl502d9a52009-07-26 15:02:41 +000053 platforms, it is a file-like object whose :attr:`!file` attribute is the
Christian Heimes81ee3ef2008-05-04 22:42:01 +000054 underlying true file object. This file-like object can be used in a
Christian Heimes3ecfea712008-02-09 20:51:34 +000055 :keyword:`with` statement, just like a normal file.
Christian Heimes7f044312008-01-06 17:05:40 +000056
Georg Brandl116aa622007-08-15 14:28:22 +000057
Georg Brandl14dfede2010-05-21 21:12:07 +000058.. 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 +000059
Christian Heimes81ee3ef2008-05-04 22:42:01 +000060 This function operates exactly as :func:`TemporaryFile` does, except that
61 the file is guaranteed to have a visible name in the file system (on
62 Unix, the directory entry is not unlinked). That name can be retrieved
Senthil Kumarana6bac952011-07-04 11:28:30 -070063 from the :attr:`name` attribute of the file object. Whether the name can be
Christian Heimes81ee3ef2008-05-04 22:42:01 +000064 used to open the file a second time, while the named temporary file is
65 still open, varies across platforms (it can be so used on Unix; it cannot
66 on Windows NT or later). If *delete* is true (the default), the file is
67 deleted as soon as it is closed.
Georg Brandl502d9a52009-07-26 15:02:41 +000068 The returned object is always a file-like object whose :attr:`!file`
Christian Heimes81ee3ef2008-05-04 22:42:01 +000069 attribute is the underlying true file object. This file-like object can
70 be used in a :keyword:`with` statement, just like a normal file.
Georg Brandl116aa622007-08-15 14:28:22 +000071
Georg Brandl116aa622007-08-15 14:28:22 +000072
Georg Brandl14dfede2010-05-21 21:12:07 +000073.. 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 +000074
Christian Heimes81ee3ef2008-05-04 22:42:01 +000075 This function operates exactly as :func:`TemporaryFile` does, except that
76 data is spooled in memory until the file size exceeds *max_size*, or
77 until the file's :func:`fileno` method is called, at which point the
78 contents are written to disk and operation proceeds as with
79 :func:`TemporaryFile`.
Georg Brandl116aa622007-08-15 14:28:22 +000080
Christian Heimes81ee3ef2008-05-04 22:42:01 +000081 The resulting file has one additional method, :func:`rollover`, which
82 causes the file to roll over to an on-disk file regardless of its size.
Georg Brandl116aa622007-08-15 14:28:22 +000083
Christian Heimes81ee3ef2008-05-04 22:42:01 +000084 The returned object is a file-like object whose :attr:`_file` attribute
85 is either a :class:`StringIO` object or a true file object, depending on
86 whether :func:`rollover` has been called. This file-like object can be
87 used in a :keyword:`with` statement, just like a normal file.
88
R David Murrayca76ea12012-10-06 18:32:39 -040089 .. versionchanged:: 3.3
90 the truncate method now accepts a ``size`` argument.
91
Christian Heimes81ee3ef2008-05-04 22:42:01 +000092
Nick Coghlan543af752010-10-24 11:23:25 +000093.. function:: TemporaryDirectory(suffix='', prefix='tmp', dir=None)
94
95 This function creates a temporary directory using :func:`mkdtemp`
96 (the supplied arguments are passed directly to the underlying function).
97 The resulting object can be used as a context manager (see
98 :ref:`context-managers`). On completion of the context (or destruction
99 of the temporary directory object), the newly created temporary directory
100 and all its contents are removed from the filesystem.
101
Senthil Kumarana6bac952011-07-04 11:28:30 -0700102 The directory name can be retrieved from the :attr:`name` attribute
Nick Coghlan543af752010-10-24 11:23:25 +0000103 of the returned object.
104
105 The directory can be explicitly cleaned up by calling the
106 :func:`cleanup` method.
107
108 .. versionadded:: 3.2
109
110
Georg Brandl7f01a132009-09-16 15:58:14 +0000111.. function:: mkstemp(suffix='', prefix='tmp', dir=None, text=False)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000112
113 Creates a temporary file in the most secure manner possible. There are
114 no race conditions in the file's creation, assuming that the platform
115 properly implements the :const:`os.O_EXCL` flag for :func:`os.open`. The
116 file is readable and writable only by the creating user ID. If the
117 platform uses permission bits to indicate whether a file is executable,
118 the file is executable by no one. The file descriptor is not inherited
119 by child processes.
120
121 Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible
122 for deleting the temporary file when done with it.
123
124 If *suffix* is specified, the file name will end with that suffix,
125 otherwise there will be no suffix. :func:`mkstemp` does not put a dot
126 between the file name and the suffix; if you need one, put it at the
127 beginning of *suffix*.
128
129 If *prefix* is specified, the file name will begin with that prefix;
130 otherwise, a default prefix is used.
131
132 If *dir* is specified, the file will be created in that directory;
133 otherwise, a default directory is used. The default directory is chosen
134 from a platform-dependent list, but the user of the application can
135 control the directory location by setting the *TMPDIR*, *TEMP* or *TMP*
136 environment variables. There is thus no guarantee that the generated
137 filename will have any nice properties, such as not requiring quoting
138 when passed to external commands via ``os.popen()``.
139
140 If *text* is specified, it indicates whether to open the file in binary
141 mode (the default) or text mode. On some platforms, this makes no
142 difference.
143
144 :func:`mkstemp` returns a tuple containing an OS-level handle to an open
145 file (as would be returned by :func:`os.open`) and the absolute pathname
146 of that file, in that order.
147
148
Georg Brandl7f01a132009-09-16 15:58:14 +0000149.. function:: mkdtemp(suffix='', prefix='tmp', dir=None)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000150
151 Creates a temporary directory in the most secure manner possible. There
152 are no race conditions in the directory's creation. The directory is
153 readable, writable, and searchable only by the creating user ID.
154
155 The user of :func:`mkdtemp` is responsible for deleting the temporary
156 directory and its contents when done with it.
157
158 The *prefix*, *suffix*, and *dir* arguments are the same as for
159 :func:`mkstemp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161 :func:`mkdtemp` returns the absolute pathname of the new directory.
162
Georg Brandl116aa622007-08-15 14:28:22 +0000163
Georg Brandl7f01a132009-09-16 15:58:14 +0000164.. function:: mktemp(suffix='', prefix='tmp', dir=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166 .. deprecated:: 2.3
167 Use :func:`mkstemp` instead.
168
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000169 Return an absolute pathname of a file that did not exist at the time the
170 call is made. The *prefix*, *suffix*, and *dir* arguments are the same
171 as for :func:`mkstemp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173 .. warning::
174
Georg Brandl36ab1ef2009-01-03 21:17:04 +0000175 Use of this function may introduce a security hole in your program. By
176 the time you get around to doing anything with the file name it returns,
177 someone else may have beaten you to the punch. :func:`mktemp` usage can
178 be replaced easily with :func:`NamedTemporaryFile`, passing it the
179 ``delete=False`` parameter::
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000180
181 >>> f = NamedTemporaryFile(delete=False)
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000182 >>> f
183 <open file '<fdopen>', mode 'w+b' at 0x384698>
184 >>> f.name
185 '/var/folders/5q/5qTPn6xq2RaWqk+1Ytw3-U+++TI/-Tmp-/tmpG7V1Y0'
186 >>> f.write("Hello World!\n")
187 >>> f.close()
188 >>> os.unlink(f.name)
189 >>> os.path.exists(f.name)
190 False
Georg Brandl116aa622007-08-15 14:28:22 +0000191
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000192The module uses two global variables that tell it how to construct a
193temporary name. They are initialized at the first call to any of the
194functions above. The caller may change them, but this is discouraged; use
195the appropriate function arguments, instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
197
198.. data:: tempdir
199
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000200 When set to a value other than ``None``, this variable defines the
201 default value for the *dir* argument to all the functions defined in this
202 module.
Georg Brandl116aa622007-08-15 14:28:22 +0000203
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000204 If ``tempdir`` is unset or ``None`` at any call to any of the above
205 functions, Python searches a standard list of directories and sets
206 *tempdir* to the first one which the calling user can create files in.
207 The list is:
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209 #. The directory named by the :envvar:`TMPDIR` environment variable.
210
211 #. The directory named by the :envvar:`TEMP` environment variable.
212
213 #. The directory named by the :envvar:`TMP` environment variable.
214
215 #. A platform-specific location:
216
Georg Brandl116aa622007-08-15 14:28:22 +0000217 * 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
232
Georg Brandl116aa622007-08-15 14:28:22 +0000233.. function:: gettempprefix()
234
235 Return the filename prefix used to create temporary files. This does not
Georg Brandl4b26ff82008-08-04 07:24:52 +0000236 contain the directory component.
Georg Brandl116aa622007-08-15 14:28:22 +0000237
Nick Coghlan543af752010-10-24 11:23:25 +0000238
239Examples
240--------
241
242Here are some examples of typical usage of the :mod:`tempfile` module::
243
244 >>> import tempfile
245
246 # create a temporary file and write some data to it
247 >>> fp = tempfile.TemporaryFile()
Ross Lagerwall810b94a2011-04-10 09:30:04 +0200248 >>> fp.write(b'Hello world!')
Nick Coghlan543af752010-10-24 11:23:25 +0000249 # read data from file
250 >>> fp.seek(0)
251 >>> fp.read()
Ross Lagerwall810b94a2011-04-10 09:30:04 +0200252 b'Hello world!'
Nick Coghlan543af752010-10-24 11:23:25 +0000253 # close the file, it will be removed
254 >>> fp.close()
255
256 # create a temporary file using a context manager
257 >>> with tempfile.TemporaryFile() as fp:
Ross Lagerwall810b94a2011-04-10 09:30:04 +0200258 ... fp.write(b'Hello world!')
Nick Coghlan543af752010-10-24 11:23:25 +0000259 ... fp.seek(0)
260 ... fp.read()
Ross Lagerwall810b94a2011-04-10 09:30:04 +0200261 b'Hello world!'
Nick Coghlan543af752010-10-24 11:23:25 +0000262 >>>
263 # file is now closed and removed
264
265 # create a temporary directory using the context manager
266 >>> with tempfile.TemporaryDirectory() as tmpdirname:
Ross Lagerwall810b94a2011-04-10 09:30:04 +0200267 ... print('created temporary directory', tmpdirname)
Nick Coghlan543af752010-10-24 11:23:25 +0000268 >>>
269 # directory and contents have been removed
270