Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between 'with open(...)' and 'with closing(open(...))'

Tags:

python

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?

like image 352
Bodo Thiesen Avatar asked Sep 02 '16 23:09

Bodo Thiesen


People also ask

What is the difference between open and with open in python?

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.

What is close and open?

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.

What is the difference in opening a file using open () function or using with statement to open?

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.


1 Answers

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.

like image 183
user2357112 supports Monica Avatar answered Sep 23 '22 22:09

user2357112 supports Monica