blob: 5caea677e3a2f098c9426c05d927ffd0aee41071 [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
15This module generates temporary files and directories. It works on all
Georg Brandle6bcc912008-05-12 18:05:20 +000016supported platforms. It provides three new functions,
17:func:`NamedTemporaryFile`, :func:`mkstemp`, and :func:`mkdtemp`, which should
18eliminate all remaining need to use the insecure :func:`mktemp` function.
19Temporary file names created by this module no longer contain the process ID;
20instead a string of six random characters is used.
Georg Brandl116aa622007-08-15 14:28:22 +000021
Christian Heimes81ee3ef2008-05-04 22:42:01 +000022Also, all the user-callable functions now take additional arguments which
23allow direct control over the location and name of temporary files. It is
24no longer necessary to use the global *tempdir* and *template* variables.
25To maintain backward compatibility, the argument order is somewhat odd; it
26is recommended to use keyword arguments for clarity.
Georg Brandl116aa622007-08-15 14:28:22 +000027
Nick Coghlan543af752010-10-24 11:23:25 +000028The module defines the following user-callable items:
Georg Brandl116aa622007-08-15 14:28:22 +000029
Georg Brandl14dfede2010-05-21 21:12:07 +000030.. function:: TemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None)
Georg Brandl116aa622007-08-15 14:28:22 +000031
Antoine Pitrou11cb9612010-09-15 11:11:28 +000032 Return a :term:`file-like object` that can be used as a temporary storage area.
Christian Heimes81ee3ef2008-05-04 22:42:01 +000033 The file is created using :func:`mkstemp`. It will be destroyed as soon
Georg Brandl116aa622007-08-15 14:28:22 +000034 as it is closed (including an implicit close when the object is garbage
Christian Heimes81ee3ef2008-05-04 22:42:01 +000035 collected). Under Unix, the directory entry for the file is removed
36 immediately after the file is created. Other platforms do not support
37 this; your code should not rely on a temporary file created using this
38 function having or not having a visible name in the file system.
Georg Brandl116aa622007-08-15 14:28:22 +000039
Christian Heimes81ee3ef2008-05-04 22:42:01 +000040 The *mode* parameter defaults to ``'w+b'`` so that the file created can
41 be read and written without being closed. Binary mode is used so that it
42 behaves consistently on all platforms without regard for the data that is
Georg Brandl14dfede2010-05-21 21:12:07 +000043 stored. *buffering*, *encoding* and *newline* are interpreted as for
44 :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +000045
46 The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`.
47
Christian Heimes7f044312008-01-06 17:05:40 +000048 The returned object is a true file object on POSIX platforms. On other
Georg Brandl502d9a52009-07-26 15:02:41 +000049 platforms, it is a file-like object whose :attr:`!file` attribute is the
Christian Heimes81ee3ef2008-05-04 22:42:01 +000050 underlying true file object. This file-like object can be used in a
Christian Heimes3ecfea712008-02-09 20:51:34 +000051 :keyword:`with` statement, just like a normal file.
Christian Heimes7f044312008-01-06 17:05:40 +000052
Georg Brandl116aa622007-08-15 14:28:22 +000053
Georg Brandl14dfede2010-05-21 21:12:07 +000054.. 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 +000055
Christian Heimes81ee3ef2008-05-04 22:42:01 +000056 This function operates exactly as :func:`TemporaryFile` does, except that
57 the file is guaranteed to have a visible name in the file system (on
58 Unix, the directory entry is not unlinked). That name can be retrieved
59 from the :attr:`name` member of the file object. Whether the name can be
60 used to open the file a second time, while the named temporary file is
61 still open, varies across platforms (it can be so used on Unix; it cannot
62 on Windows NT or later). If *delete* is true (the default), the file is
63 deleted as soon as it is closed.
Georg Brandl502d9a52009-07-26 15:02:41 +000064 The returned object is always a file-like object whose :attr:`!file`
Christian Heimes81ee3ef2008-05-04 22:42:01 +000065 attribute is the underlying true file object. This file-like object can
66 be used in a :keyword:`with` statement, just like a normal file.
Georg Brandl116aa622007-08-15 14:28:22 +000067
Georg Brandl116aa622007-08-15 14:28:22 +000068
Georg Brandl14dfede2010-05-21 21:12:07 +000069.. 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 +000070
Christian Heimes81ee3ef2008-05-04 22:42:01 +000071 This function operates exactly as :func:`TemporaryFile` does, except that
72 data is spooled in memory until the file size exceeds *max_size*, or
73 until the file's :func:`fileno` method is called, at which point the
74 contents are written to disk and operation proceeds as with
75 :func:`TemporaryFile`.
Georg Brandl116aa622007-08-15 14:28:22 +000076
Christian Heimes81ee3ef2008-05-04 22:42:01 +000077 The resulting file has one additional method, :func:`rollover`, which
78 causes the file to roll over to an on-disk file regardless of its size.
Georg Brandl116aa622007-08-15 14:28:22 +000079
Christian Heimes81ee3ef2008-05-04 22:42:01 +000080 The returned object is a file-like object whose :attr:`_file` attribute
81 is either a :class:`StringIO` object or a true file object, depending on
82 whether :func:`rollover` has been called. This file-like object can be
83 used in a :keyword:`with` statement, just like a normal file.
84
85
Nick Coghlan543af752010-10-24 11:23:25 +000086.. function:: TemporaryDirectory(suffix='', prefix='tmp', dir=None)
87
88 This function creates a temporary directory using :func:`mkdtemp`
89 (the supplied arguments are passed directly to the underlying function).
90 The resulting object can be used as a context manager (see
91 :ref:`context-managers`). On completion of the context (or destruction
92 of the temporary directory object), the newly created temporary directory
93 and all its contents are removed from the filesystem.
94
95 The directory name can be retrieved from the :attr:`name` member
96 of the returned object.
97
98 The directory can be explicitly cleaned up by calling the
99 :func:`cleanup` method.
100
101 .. versionadded:: 3.2
102
103
Georg Brandl7f01a132009-09-16 15:58:14 +0000104.. function:: mkstemp(suffix='', prefix='tmp', dir=None, text=False)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000105
106 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.
113
114 Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible
115 for deleting the temporary file when done with it.
116
117 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*.
121
122 If *prefix* is specified, the file name will begin with that prefix;
123 otherwise, a default prefix is used.
124
125 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()``.
132
133 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.
136
137 :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.
140
141
Georg Brandl7f01a132009-09-16 15:58:14 +0000142.. function:: mkdtemp(suffix='', prefix='tmp', dir=None)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000143
144 Creates a temporary directory in the most secure manner possible. There
145 are no race conditions in the directory's creation. The directory is
146 readable, writable, and searchable only by the creating user ID.
147
148 The user of :func:`mkdtemp` is responsible for deleting the temporary
149 directory and its contents when done with it.
150
151 The *prefix*, *suffix*, and *dir* arguments are the same as for
152 :func:`mkstemp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154 :func:`mkdtemp` returns the absolute pathname of the new directory.
155
Georg Brandl116aa622007-08-15 14:28:22 +0000156
Georg Brandl7f01a132009-09-16 15:58:14 +0000157.. function:: mktemp(suffix='', prefix='tmp', dir=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159 .. deprecated:: 2.3
160 Use :func:`mkstemp` instead.
161
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000162 Return an absolute pathname of a file that did not exist at the time the
163 call is made. The *prefix*, *suffix*, and *dir* arguments are the same
164 as for :func:`mkstemp`.
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166 .. warning::
167
Georg Brandl36ab1ef2009-01-03 21:17:04 +0000168 Use of this function may introduce a security hole in your program. By
169 the time you get around to doing anything with the file name it returns,
170 someone else may have beaten you to the punch. :func:`mktemp` usage can
171 be replaced easily with :func:`NamedTemporaryFile`, passing it the
172 ``delete=False`` parameter::
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000173
174 >>> f = NamedTemporaryFile(delete=False)
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000175 >>> f
176 <open file '<fdopen>', mode 'w+b' at 0x384698>
177 >>> f.name
178 '/var/folders/5q/5qTPn6xq2RaWqk+1Ytw3-U+++TI/-Tmp-/tmpG7V1Y0'
179 >>> f.write("Hello World!\n")
180 >>> f.close()
181 >>> os.unlink(f.name)
182 >>> os.path.exists(f.name)
183 False
Georg Brandl116aa622007-08-15 14:28:22 +0000184
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000185The module uses two global variables that tell it how to construct a
186temporary name. They are initialized at the first call to any of the
187functions above. The caller may change them, but this is discouraged; use
188the appropriate function arguments, instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190
191.. data:: tempdir
192
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000193 When set to a value other than ``None``, this variable defines the
194 default value for the *dir* argument to all the functions defined in this
195 module.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000197 If ``tempdir`` is unset or ``None`` at any call to any of the above
198 functions, Python searches a standard list of directories and sets
199 *tempdir* to the first one which the calling user can create files in.
200 The list is:
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202 #. The directory named by the :envvar:`TMPDIR` environment variable.
203
204 #. The directory named by the :envvar:`TEMP` environment variable.
205
206 #. The directory named by the :envvar:`TMP` environment variable.
207
208 #. A platform-specific location:
209
Georg Brandl116aa622007-08-15 14:28:22 +0000210 * On Windows, the directories :file:`C:\\TEMP`, :file:`C:\\TMP`,
211 :file:`\\TEMP`, and :file:`\\TMP`, in that order.
212
213 * On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and
214 :file:`/usr/tmp`, in that order.
215
216 #. As a last resort, the current working directory.
217
218
219.. function:: gettempdir()
220
221 Return the directory currently selected to create temporary files in. If
222 :data:`tempdir` is not ``None``, this simply returns its contents; otherwise,
223 the search described above is performed, and the result returned.
224
225
Georg Brandl116aa622007-08-15 14:28:22 +0000226.. function:: gettempprefix()
227
228 Return the filename prefix used to create temporary files. This does not
Georg Brandl4b26ff82008-08-04 07:24:52 +0000229 contain the directory component.
Georg Brandl116aa622007-08-15 14:28:22 +0000230
Nick Coghlan543af752010-10-24 11:23:25 +0000231
232Examples
233--------
234
235Here are some examples of typical usage of the :mod:`tempfile` module::
236
237 >>> import tempfile
238
239 # create a temporary file and write some data to it
240 >>> fp = tempfile.TemporaryFile()
241 >>> fp.write('Hello world!')
242 # read data from file
243 >>> fp.seek(0)
244 >>> fp.read()
245 'Hello world!'
246 # close the file, it will be removed
247 >>> fp.close()
248
249 # create a temporary file using a context manager
250 >>> with tempfile.TemporaryFile() as fp:
251 ... fp.write('Hello world!')
252 ... fp.seek(0)
253 ... fp.read()
254 'Hello world!'
255 >>>
256 # file is now closed and removed
257
258 # create a temporary directory using the context manager
259 >>> with tempfile.TemporaryDirectory() as tmpdirname:
260 ... print 'created temporary directory', tmpdirname
261 >>>
262 # directory and contents have been removed
263