summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGeorg Brandl <georg@python.org>2008-07-16 23:35:54 (GMT)
committerGeorg Brandl <georg@python.org>2008-07-16 23:35:54 (GMT)
commita66bb0a741060b35151673dffb0d5b87307aa7e9 (patch)
tree787db3acd08046edfe382ebbb6c365b4f4afc45d
parent0a34baf1fc10ffd61f4e9a8d053008dd57930fff (diff)
downloadcpython-a66bb0a741060b35151673dffb0d5b87307aa7e9.zip
cpython-a66bb0a741060b35151673dffb0d5b87307aa7e9.tar.gz
cpython-a66bb0a741060b35151673dffb0d5b87307aa7e9.tar.bz2
#3388: add a paragraph about using "with" for file objects.
-rw-r--r--Doc/tutorial/inputoutput.rst10
1 files changed, 10 insertions, 0 deletions
diff --git a/Doc/tutorial/inputoutput.rst b/Doc/tutorial/inputoutput.rst
index fe33d12..1b344e6 100644
--- a/Doc/tutorial/inputoutput.rst
+++ b/Doc/tutorial/inputoutput.rst
@@ -348,6 +348,16 @@ attempts to use the file object will automatically fail. ::
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.