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?

8
  • 6
    when you open the file using with, python takes care of it. Commented Apr 10, 2019 at 9:55
  • This might be helpful: stackoverflow.com/questions/17459867/… Commented Apr 10, 2019 at 9:55
  • @ConsistentProgrammer and what about the urlopen? Commented Apr 10, 2019 at 9:56
  • 1
    @Luis Use with for that as well, and it will be done automatically. Commented Apr 10, 2019 at 9:58
  • 1
    What does the python documentation say about urlopen? Commented Apr 10, 2019 at 9:58

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.