From a98bdf12f15e19b86ef90050c2d911b8b34915e5 Mon Sep 17 00:00:00 2001 From: NJL Date: Tue, 3 Jun 2025 16:03:27 -0400 Subject: [PATCH] Add example using 'with' statement and urlopen --- .../urlopen-example/with_urlopen_example.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 context-managers/urlopen-example/with_urlopen_example.py 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