Is a call to `close ()` redundant if the file is opened with a `with` statement

Suppose I have the following code:

with open('somefile.txt') as my_file:
    # some processing
    my_file.close()

      

Is it my_file.close()

redundant?

+3


source to share


4 answers


Yes it is; Also, it doesn't guarantee that yours close()

will always be executed. (for example, if it exists Exception

).

with open('somefile.txt') as my_file:
    1/0 # raise Exception
    my_file.close() # Your close() call is never going to be called

      

But the __exit__()

operator function with

is always executed because it follows try...except...finally

.

The with statement is used to wrap the execution of a block using methods defined by the context manager (see the Statement section of Context Managers). This allows for the usual try ... except ... finally using templates, which should be encapsulated for easy reuse.

The __exit __ () method for managing the context is called. If the exception caused an exit from the window, its type, value and trace are passed as arguments to __exit __ ()



You can check that the file was closed right after the instruction with

usingclosed

>>> with open('somefile.txt') as f:
...     pass
>>> f.closed
# True

      

Source for my answer:

+1


source


Yes. Exiting the block with

will close the file.



However, this is not necessarily true for objects that are not files. Typically, exiting context should initiate an operation that is conceptually equivalent to "closing", but can in fact __exit__

be overloaded to execute whatever code the object desires.

+2


source


The statement with

creates the runtime context. Python creates a thread object file

and tells it that it is entering the runtime context. When the code is complete, Python tells the thread object to exit the runtime context, and the thread object calls its own close () method.

+1


source


yes the with statement takes care of that

as you can see in the documentation :

The context management method is called __exit__()

. If an exception caused the package to exit, its type, value, and trace are passed as arguments __exit__()

.

In case of files, the method __exit__()

will close the file

0


source







All Articles