Python - How to make sure resource is closed

Viewed 259

I want to close f before returning from the method. I added finally blocked but it needs initialization. What to initialize it with?

def test_close_resource(url):
    try:
        f = urllib2.urlopen(url)
        if f.code == 200:
            return True
    except Exception as error:
        return False
    finally:
        f.close()
2 Answers

Open the connection within a context manager using with as:

import urllib.request
with urllib.request.urlopen('http://www.python.org/') as f:
    print(f.read(300))

The connection gets closed automatically when it comes out of the context manager block defined with with keyword.

I think that what you're looking for is the with clause -

with urllib.request.urlopen('http://python.org/') as response:pass
Related