Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Download Files from Internet with Progress Bar in Python
Download a file from the internet while displaying a text progress bar in the terminal.
import urllib.request
import sys
def download_with_progress(url, filename):
"""Download a file with a simple text progress bar."""
def report_hook(block_count, block_size, total_size):
downloaded = block_count * block_size
if total_size > 0:
percent = min(100, int(downloaded * 100 …
Automatically Download the Latest Software Release from GitHub with Python
Use the GitHub API to fetch the latest release metadata and download the first asset (binary or archive) to a local directory.
import requests
import sys
from pathlib import Path
def download_latest_release(owner: str, repo: str, output_dir: str = ".") -> None:
"""Download the latest release asset from a GitHub repository."""
url = f"https://api.github.com/repos/{owner}/{repo}/releases/latest"
response = requests.get(url)
res…
Download Images from a Web Page Automatically in Python
Scrape all images from a webpage, filter by extension, and save them to a local folder using requests and BeautifulSoup.
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import os
def download_images(url, output_folder="downloaded_images"):
"""Download all images from a given URL."""
os.makedirs(output_folder, exist_ok=True)
response = requests.get(url)
response.raise_for_status()
…
How to Auto Organize Downloads by File Extension in Python
A Python script that sorts files in a directory into subfolders based on their file extensions, creating folders automatically.
import os
import shutil
from pathlib import Path
def organize_downloads(download_dir="~/Downloads"):
"""Move files in a directory into subfolders based on file extension."""
download_path = Path(download_dir).expanduser()
if not download_path.exists():
print(f"Directory not found: {download_p…
How to Automatically Download Every Favicon from a List of Websites in Python
Download each website's favicon.ico file by constructing its URL, making a GET request, and saving the binary content locally.
import requests
from urllib.parse import urlparse
import os
websites = [
"https://www.google.com",
"https://www.github.com",
"https://www.stackoverflow.com"
]
def download_favicon(url):
parsed = urlparse(url)
favicon_url = f"{parsed.scheme}://{parsed.netloc}/favicon.ico"
response = requests.g…
How to Download All Assets from GitHub Releases in Python
Downloads every asset attached to the latest GitHub release of a repository, saving them locally using the GitHub API and Python's requests and pathlib libraries.
import requests
import os
import zipfile
from pathlib import Path
def download_github_release_assets(owner: str, repo: str, output_dir: str = "release_assets") -> None:
"""Downloads all assets from the latest release of a GitHub repository."""
releases_url = f"https://api.github.com/repos/{owner}/{repo}/relea…
How to Download a GitHub Repository as a ZIP File in Python
Download any public GitHub repository as a ZIP file using the GitHub API and Python's requests and zipfile modules.
import requests
import zipfile
import io
import os
def download_github_repo_as_zip(repo_url, output_path='.'):
"""
Download a GitHub repository as a ZIP file.
Args:
repo_url (str): Full GitHub repository URL (e.g., 'https://github.com/username/repo')
output_path (str): Directory to sa…
How to Download a List of URLs to a Directory in Python
This script downloads a list of URLs into a specified directory, creating the folder if needed and keeping original filenames.
import urllib.request
from pathlib import Path
def download_urls(url_list, directory):
"""Download each URL in url_list into directory, keeping original filenames."""
save_dir = Path(directory)
save_dir.mkdir(parents=True, exist_ok=True)
for url in url_list:
filename = url.rstrip('/').spl…
How to automatically organize your Downloads folder by file type in Python
This script scans the Downloads folder and moves files into sub-folders based on their extensions (e.g., Images, Documents, Videos).
import os
import shutil
from pathlib import Path
def organize_downloads_folder(downloads_path=None):
if downloads_path is None:
downloads_path = str(Path.home() / "Downloads")
if not os.path.exists(downloads_path):
print(f"Path {downloads_path} does not exist.")
return
fi…
Mock Azure Blob Upload and Download in Python
Simulate Azure Blob Storage upload and download operations with a lightweight in-memory mock class for testing.
import io
import json
from datetime import datetime, timezone
class MockBlob:
def __init__(self, name):
self.name = name
self.content = b""
self.properties = {
"last_modified": datetime.now(timezone.utc).isoformat(),
"size": 0,
}
def upload(self, data, …
How to Speed Up Downloads with ThreadPoolExecutor in Python
Compare sequential and thread-pool download loops to measure real speedup when I/O s bound.
import time
import threading
from concurrent.futures import ThreadPoolExecutor
def download_file(file_id):
"""Simulate fetching a file by sleeping briefly."""
time.sleep(0.2) # pretend network latency
return f"file_{file_id}"
def sequential_downloads(num_files):
"""Process files one at a time."""
…
How to Mock Content-Disposition and Extract Filename in Python
Parse and mock Content-Disposition headers in Python to extract filenames, handling both plain and RFC 5987 encoded values.
import os
from pathlib import Path
import re
from unittest.mock import patch
def get_filename_from_content_disposition(header_value):
"""
Extract filename from a Content-Disposition header value.
Supports both filename and filename* parameters (RFC 5987).
"""
if not header_value:
return No…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.