Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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 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 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.