From my understanding,
with open(...) as x:
is supposed to close the file once the with
statement completed. However, now I see
with closing(open(...)) as x:
in one place, looked around and figured out, that closing
is supposed to close the file upon finish of the with
statement.
So, what's the difference between closing the file and closing
the file?
Within the block of code opened by “with”, our file is open, and can be read from freely. However, once Python exits from the “with” block, the file is automatically closed.
open and close means the preparation of the grave or niche for interment and completing and closing the grave after the interment. Sample 1Sample 2Sample 3. Based on 2 documents.
Benefits of calling open() using “with statement” So, it reduces the number of lines of code and reduces the chances of bug. If we have opened a file using “with statement” and an exception comes inside the execution block of “with statement”. Then file will be closed before control moves to the except block.
Assuming that's contextlib.closing
and the standard, built-in open
, closing
is redundant here. It's a wrapper to allow you to use with
statements with objects that have a close
method, but don't support use as context managers. Since the file objects returned by open
are context managers, closing
is unneeded.
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