Bodo Thiesen
Bodo Thiesen

Reputation: 2514

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

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?

Upvotes: 7

Views: 2082

Answers (1)

user2357112
user2357112

Reputation: 281958

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.

Upvotes: 18

Related Questions