3

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?

SuperKogito
  • 2,998
  • 3
  • 16
  • 37
Luis
  • 1,305
  • 5
  • 19
  • 46

2 Answers2

3

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.

Nick
  • 3,454
  • 6
  • 33
  • 56
1

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.