Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(48197)

Unified Diff: Doc/library/tempfile.rst

Issue 5178: Add context manager for temporary directory
Patch Set: Created 8 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « no previous file | Lib/tempfile.py » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: Doc/library/tempfile.rst
===================================================================
--- Doc/library/tempfile.rst (revision 69412)
+++ Doc/library/tempfile.rst (working copy)
@@ -29,7 +29,7 @@
To maintain backward compatibility, the argument order is somewhat odd; it
is recommended to use keyword arguments for clarity.
-The module defines the following user-callable functions:
+The module defines the following user-callable items:
.. function:: TemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]])
@@ -153,6 +153,18 @@
.. versionadded:: 2.3
+.. class:: TemporaryDirectory([suffix=''[, prefix='tmp'[, dir=None]]])
+
+ Creates a temporary directory using :func:`mkdtemp`. The class can
+ used as a context manager (see :ref:`context-managers`). On exiting
+ of the context, the temporary directory and all its contents are
+ removed. The directory can be manually be cleaned up by calling the
+ :func:`cleanup` method. The directory name can be retrieved from the
+ :attr:`name` member of the object.
+
+ .. versionadded:: 2.7
+
+
.. function:: mktemp([suffix=''[, prefix='tmp'[, dir=None]]])
.. deprecated:: 2.3
@@ -250,3 +262,36 @@
.. versionadded:: 1.5.2
+
+Examples
+--------
+
+Here are some examples of typical usage of the :mod:`tempfile` module::
+
+ >>> import tempfile
+
+ # create a temporary file and write some data to it
+ >>> fp = tempfile.TemporaryFile()
+ >>> fp.write('Hello world!')
+ # read data from file
+ >>> fp.seek(0)
+ >>> fp.read()
+ 'Hello world!'
+ # close the file, it will be removed
+ >>> fp.close()
+
+ # create a temporary file using a context manager
+ >>> with tempfile.TemporaryFile() as fp:
+ ... fp.write('Hello world!')
+ ... fp.seek(0)
+ ... fp.read()
+ 'Hello world!'
+ >>>
+ # file is now closed and removed
+
+ # create a temporary directory using the context manager
+ >>> with tempfile.TemporaryDirectory() as tmpdirname:
+ ... print 'created temporary directory', tmpdirname
+ >>>
+ # directory and contents have been removed
+
« no previous file with comments | « no previous file | Lib/tempfile.py » ('j') | no next file with comments »

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+