diff --git a/context-managers/urlopen-example/with_urlopen_example.py b/context-managers/urlopen-example/with_urlopen_example.py new file mode 100644 index 0000000000..f3a9267cad --- /dev/null +++ b/context-managers/urlopen-example/with_urlopen_example.py @@ -0,0 +1,16 @@ + +""" +Using the 'with' statement to open a URL + +This example demonstrates how Python's 'with' statement can be used +to manage resources like HTTP connections when working with URLS +""" + +from urllib.request import urlopen + +url = "https://www.python.org" + +# 'with' ensures that the connection automatically closes +with urlopen(url) as response: + html = response.read() + print(html[:200]) # prints first 200 bytes \ No newline at end of file