Search code examples
pythonurllib2

Python - How to make sure resource is closed


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()

Solution

  • 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.