Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions context-managers/urlopen-example/with_urlopen_example.py
Original file line number Diff line number Diff line change
@@ -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