[Python-checkins] r65048 - python/trunk/Doc/tutorial/inputoutput.rst

georg.brandl python-checkins at python.org
Thu Jul 17 01:35:55 CEST 2008


Author: georg.brandl
Date: Thu Jul 17 01:35:54 2008
New Revision: 65048

Log:
#3388: add a paragraph about using "with" for file objects.


Modified:
   python/trunk/Doc/tutorial/inputoutput.rst

Modified: python/trunk/Doc/tutorial/inputoutput.rst
==============================================================================
--- python/trunk/Doc/tutorial/inputoutput.rst	(original)
+++ python/trunk/Doc/tutorial/inputoutput.rst	Thu Jul 17 01:35:54 2008
@@ -348,6 +348,16 @@
      File "<stdin>", line 1, in ?
    ValueError: I/O operation on closed file
 
+It is good practice to use the :keyword:`with` keyword when dealing with file
+objects.  This has the advantage that the file is properly closed after its
+suite finishes, even if an exception is raised on the way.  It is also much
+shorter than writing equivalent :keyword:`try`\ -\ :keyword:`finally` blocks::
+
+    >>> with open('/tmp/workfile', 'r') as f:
+    ...     read_data = f.read()
+    >>> f.closed
+    True
+
 File objects have some additional methods, such as :meth:`isatty` and
 :meth:`truncate` which are less frequently used; consult the Library Reference
 for a complete guide to file objects.


More information about the Python-checkins mailing list