Reference library
Python code samples
Easy snippets you can copy, study, and run in the browser editor.
Build a Python Script That Detects and Deletes Empty Files Across Folders
A Python script that recursively finds and removes all zero-byte files across nested directories, returning a list of deleted paths.
import os
from pathlib import Path
def find_and_delete_empty_files(root_dir: str) -> list:
"""Find and delete all empty files under root_dir. Returns list of deleted paths."""
deleted = []
for file_path in Path(root_dir).rglob('*'):
if file_path.is_file() and file_path.stat().st_size == 0:
…
How to Archive Old Files by Age in Python
Move files older than a specified number of days from a source directory to an archive directory using Python's pathlib and shutil modules.
import os
import shutil
import time
from pathlib import Path
def archive_old_files(source_dir: str, archive_dir: str, days_old: int) -> None:
cutoff_time = time.time() - (days_old * 86400) # 86400 seconds in a day
archive_path = Path(archive_dir)
archive_path.mkdir(parents=True, exist_ok=True)
for i…
Batch Rename Hundreds of Files in Python
Rename all files with a given extension inside a folder using a sequential counter and a custom prefix.
import os
from pathlib import Path
def batch_rename_files(directory: str, prefix: str, extension: str = ".txt") -> None:
"""Rename all files with given extension in directory to prefix_{counter}.ext."""
path = Path(directory)
if not path.is_dir():
print(f"Directory '{directory}' does not exist.")
…
Build a Command-Line Password Generator in Python
Generate cryptographically strong random passwords using Python's secrets module and print them for command-line use.
import secrets
import string
def generate_password(length=16):
"""Generate a cryptographically strong random password."""
alphabet = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(alphabet) for _ in range(length))
return password
if __name__ == "__main__":…
Generate Strong Random Passwords with Custom Rules in Python
Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.
import secrets
import string
def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
pool = ''
if use_lower:
pool += string.ascii_lowercase
if use_upper:
pool += string.ascii_uppercase
if use_digits:
pool += string.digits
if use_pu…
How to Create a File Organizer That Sorts Files Automatically in Python
A Python script that scans a given folder, categorizes files by extension (Images, Documents, Audio, Video, Archives, Misc), and moves them into subfolders automatically.
import os
import shutil
from pathlib import Path
FILE_CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp"],
"Documents": [".pdf", ".docx", ".txt", ".csv", ".xlsx"],
"Audio": [".mp3", ".wav", ".flac", ".aac"],
"Video": [".mp4", ".mkv", ".avi", ".mov"],
"Archives": [".zip", ".tar", ".g…
How to Generate a QR Code in Python
Generate a QR code image from a URL string using the qrcode library and save it as a PNG file.
import qrcode
# Data to encode
data = "https://www.example.com"
# Create QR code instance
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
# Add data to QR code
qr.add_data(data)
qr.make(fit=True)
# Create an image from the QR code
img = qr.…
How to Resize Hundreds of Images in Batch with Python
Resize every image in a folder to a target size using Pillow, creating a new subfolder for processed files.
import os
from PIL import Image
def resize_images_in_batch(directory, output_size=(800, 600)):
if not os.path.exists(directory):
print(f"Directory {directory} does not exist.")
return
output_dir = os.path.join(directory, "resized")
os.makedirs(output_dir, exist_ok=True)
for filename in…
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…
Monitor Website Uptime with Python
Periodically check if a website is reachable and its HTTP status is 200, logging the status with timestamps.
import requests
import time
def check_website(url):
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
return True
else:
return False
except requests.ConnectionError:
return False
except requests.Timeout:
return Fals…
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.