Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close file using with operator in Python

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 ?

like image 749
Arun Avatar asked Jan 04 '23 16:01

Arun


2 Answers

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.

like image 181
Srishan Supertramp Avatar answered Jan 06 '23 06:01

Srishan Supertramp


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).

like image 35
jamesdlin Avatar answered Jan 06 '23 04:01

jamesdlin