Is a call to `close ()` redundant if the file is opened with a `with` statement
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:
source to share
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.
source to share
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
source to share