Luis
Luis

Reputation: 1465

When it is required to close a file in Python?

Say I have the following code:

remote = urlopen('www...../file.txt')
with open(file='file', mode='wb') as local:
    local.write(remote.read())

Do I need to also do:

local.close()
remote.close()

How do I know when close() is needed and when Python takes care of it for me?

Upvotes: 3

Views: 105

Answers (2)

Kusal Hettiarachchi
Kusal Hettiarachchi

Reputation: 603

You do not have to close the file explicitly when you are using python with statement. So you are good with local object. And this post explains why you should close the remote resource explicitly.

Upvotes: 1

Nick
Nick

Reputation: 3845

If you use a context manager ( which is what the "with.." statement is) then you don't need to use the .close.

Python manages the resources for you in this case. This is a good article that goes into the detail of how it works.

Its good practice to use context managers whenever possible, and you can create your own using the contextlib library.

Upvotes: 3

Related Questions