From 9c889d920ccffff4d0857c676a81b1dd9629e6d7 Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Sat, 18 Jul 2009 21:28:14 -0400 Subject: [PATCH] finished #with section --- files.html | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/files.html b/files.html index 4039639..fe4c577 100644 --- a/files.html +++ b/files.html @@ -212,9 +212,13 @@ ValueError: I/O operation on closed file. a_character = a_file.read(1) print(a_character) -

This code calls open(), but it never calls a_file.close(). The with statement starts a code block, like an if statement or a for loop. Inside this code block, you can use the variable a_file as the file object returned from the call to open(). All the regular file object methods are available — seek(), read(), whatever you need. When the with block ends, Python calls a_file.close() method automatically. +

This code calls open(), but it never calls a_file.close(). The with statement starts a code block, like an if statement or a for loop. Inside this code block, you can use the variable a_file as the file object returned from the call to open(). All the regular file object methods are available — seek(), read(), whatever you need. When the with block ends, Python calls a_file.close() automatically. -

FIXME other with examples +

Here’s the kicker: no matter how or when you exit the with block, Python will close that file… even if you “exit” it via an unhandled exception. That’s right, even if your code raises an exception and your entire program comes to a screeching halt, that file will get closed. Guaranteed. + +

+

The with statement is not limited to standard file objects. You can also use it with compressed file objects from gzip.GzipFile and bz2.BZ2File (example). Nor is it limited to files; you can use it in unit testing to test that certain exceptions are raised when expected (example). +

Reading Data One Line At A Time