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
withstatement is not limited to standard file objects. You can also use it with compressed file objects fromgzip.GzipFileandbz2.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). +