Skip to content

Add example using 'with' statement and urlopen #672

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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