I have a question regarding file closing in python with
operator
import os
with os.popen('ls') as f:
print f.read()
raise IOError
print f
print f
As you can see in the above piece of code I am opening a file using with
operator, I know that the file will close automatically after exiting from the with
block, but if some error happen inside with block what will happen to the file object f
, will it close ?
Yes. From the python docs:
A context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. Context managers are normally invoked using the with statement (described in section The with statement), but can also be used by directly invoking their methods.
Commonly, context managers will implement the try..except..finally
pattern for convenience and reusability.
So, the answer to your question is yes it handles the exceptions.
Yes, an exception will invoke the context manager's usual cleanup code. From PEP 343, when describing context managers and the with
statement:
After execution of the with-block is finished, the object's
__exit__()
method is called, even if the block raised an exception, and can therefore run clean-up code.
Unrelated: you should be using subprocess.Popen
(or subprocess.call
or one of its variants) instead of os.popen
(which has been deprecated since Python 2.6).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With