Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
Build a Context Manager in Python with contextlib.contextmanager
Create a reusable context manager that safely opens and closes files using the contextlib contextmanager decorator.
from contextlib import contextmanager
@contextmanager
def managed_file(filename, mode='r'):
"""Context manager that opens and closes a file safely."""
file = open(filename, mode)
yield file
file.close()
if __name__ == "__main__":
# Write a sample file
with managed_file("sample.txt", "w") as f…
Audit File Permissions Across a Project in Python
Walks through every file and directory in a project tree and prints POSIX permissions plus owner UID.
import os
import stat
from pathlib import Path
def audit_file_permissions(project_root):
"""Walk through project_root and print path, owner, and permissions for every file."""
results = []
for root, dirs, files in os.walk(project_root):
for name in files + dirs:
full_path = os.path.joi…
Automatically Detect Corrupted Files Using SHA-256 Checksums in Python
Compute SHA-256 checksums of files and compare them to detect corruption in Python.
import hashlib
import os
def compute_sha256(filepath: str) -> str:
"""Compute SHA-256 checksum of a file."""
sha256 = hashlib.sha256()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256.update(chunk)
return sha256.hexdigest()
def validate_file_int…
Automatically Highlight Data Validation Errors Inside Excel Files in Python
Load an Excel file with openpyxl, iterate over cells, and highlight invalid data (empty, negative) with a red fill and error message.
import openpyxl
from openpyxl.styles import PatternFill
from pathlib import Path
def highlight_validation_errors(filepath: str, output_path: str = None):
wb = openpyxl.load_workbook(filepath)
red_fill = PatternFill(start_color="FF0000", end_color="FF0000", fill_type="solid")
for sheet in wb.worksheet…
Build a File Index by Relative Path Hash Map in Python
Recursively walk a directory and map normalized relative paths to absolute file paths using a defaultdict hash map.
import os
from collections import defaultdict
def build_file_index(root_dir):
index = defaultdict(list)
for dirpath, dirnames, filenames in os.walk(root_dir):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
relative_path = os.path.relpath(full_path, roo…
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:
…
Compare Two Folder Structures and Find Differences in Python
Walks two directories using os.walk, builds sets of relative paths, and prints items that exist in only one folder.
import os
def compare_folders(path1, path2):
"""
Compare the file/folder structure of two directories and print differences.
"""
def get_structure(root):
structure = set()
for dirpath, dirnames, filenames in os.walk(root):
rel_path = os.path.relpath(dirpath, root)
…
Compress and Extract ZIP Files Programmatically in Python
Create a ZIP archive with in-memory files and extract its contents to a directory using Python's stdlib zipfile and pathlib modules.
import zipfile
from pathlib import Path
import tempfile
import os
def create_sample_zip(zip_path: str, files: dict) -> None:
"""Create a ZIP file containing the given files (name -> content mapping)."""
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
for filename, content in files.ite…
Convert All Markdown Files in a Folder to HTML in Python
Batch convert every .md file in a folder to .html using the `markdown` library with the 'extra' extensions.
import os
import markdown
from pathlib import Path
def convert_md_folder_to_html(input_folder="markdown_files", output_folder="html_pages"):
input_path = Path(input_folder)
output_path = Path(output_folder)
output_path.mkdir(exist_ok=True)
for md_file in input_path.glob("*.md"):
with open…
Convert CSV Files to JSON in Python
Convert a CSV file to a JSON file using Python's built-in csv and json modules.
import csv
import json
def csv_to_json(csv_filepath, json_filepath):
"""Convert a CSV file to a JSON file."""
with open(csv_filepath, mode='r', newline='') as csv_file:
reader = csv.DictReader(csv_file)
data = [row for row in reader]
with open(json_filepath, mode='w') as json_file:
…
Convert File Data to a Dictionary in Python
This function scans a directory and converts each file's metadata (name, size, extension) into a structured dictionary for easy access.
from pathlib import Path
def convert_files_data(directory: str) -> dict:
data = {}
base = Path(directory)
if not base.exists():
return data
for file in base.iterdir():
if file.is_file():
data[file.name] = {
"size": file.stat().st_size,
"exten…
Count Files by Extension in Python
Count files in a directory grouped by file extension using Python's standard library.
from pathlib import Path
def count_files_by_extension(directory: str) -> dict[str, int]:
"""Count files in a directory grouped by file extension."""
data = {}
for path in Path(directory).iterdir():
if path.is_file():
ext = path.suffix.lower() or "(no extension)"
data[ext] =…
Detect Outliers in CSV Data Using Z-Score in Python
Read a CSV file and detect outliers in a numeric column by computing z-scores, flagging those exceeding a given threshold — no machine learning required.
import csv
import statistics
from math import sqrt
def detect_outliers(csv_path, column_name, threshold=2.0):
"""Detect outliers in a numeric column using z-score method."""
values = []
with open(csv_path, 'r', newline='') as f:
reader = csv.DictReader(f)
if column_name not in reader.field…
Export SQLite Query Results to CSV in Python
Connects to a SQLite database, runs a query, and writes the result rows and column headers to a CSV file using the standard library.
import sqlite3
import csv
def export_query_to_csv(db_path, query, csv_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute(query)
rows = cursor.fetchall()
column_names = [description[0] for description in cursor.description]
with open(csv_path, 'w', newline='', encodi…
Extract a Single Member from a ZIP Archive in Python
Extract one specific file from a ZIP archive to an output directory using the standard zipfile and pathlib modules.
import zipfile
from pathlib import Path
def extract_single_member(zip_path: str, member_name: str, output_dir: str = ".") -> Path:
"""Extract a single member from a zip archive to the output directory."""
with zipfile.ZipFile(zip_path, "r") as archive:
archive.extract(member_name, output_dir)
retu…
File Data Helper Functions in Python
Read and write text and JSON files, and list files in a directory, using pathlib-based helper functions.
from pathlib import Path
def load_text_file(filepath):
"""Read a text file and return its contents as a string."""
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not found: {filepath}")
return path.read_text(encoding="utf-8")
def save_text_file(filepath, content):
…
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…
How to Build a Dated Backup Filename with Timestamp in Python
Generate unique backup filenames with a timestamp using Python's datetime module and f-strings.
from datetime import datetime
def build_backup_filename(base_name: str, extension: str = "bak") -> str:
"""Generate a dated backup filename with timestamp."""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
return f"{base_name}_{timestamp}.{extension}"
if __name__ == "__main__":
backup_file = bu…
How to Check Disk Free Space in Python with shutil.disk_usage
This Python script uses the standard library shutil.disk_usage to report total, used, and free disk space in bytes, plus a percentage usage figure.
import shutil
def check_disk_free_space(path="/"):
"""Return a tuple of total, used, and free disk space in bytes."""
usage = shutil.disk_usage(path)
return usage.total, usage.used, usage.free
if __name__ == "__main__":
total, used, free = check_disk_free_space()
print(f"Total: {total:,} bytes"…
How to Compare Directory Trees in Python
This code recursively scans two directory trees and reports files that exist in only one directory, as well as files present in both but with different content.
from pathlib import Path
def compare_directories(path1, path2):
dir1 = Path(path1)
dir2 = Path(path2)
if not dir1.is_dir() or not dir2.is_dir():
raise ValueError("Both paths must be directories.")
files1 = {p.relative_to(dir1) for p in dir1.rglob("*") if p.is_file()}
files2 = {p.relative…
How to Convert Images Between Formats in Python
Use the Pillow library to open an image from one file format and save it to another, with error handling for missing files or conversion issues.
from PIL import Image
import sys
def convert_image_format(input_path, output_path):
try:
img = Image.open(input_path)
img.save(output_path)
print(f"Converted {input_path} to {output_path}")
except FileNotFoundError:
print(f"Error: File {input_path} not found")
sys.exit(…
How to Copy a File with shutil.copy2 in Python
Copy a file while preserving metadata like timestamps and permissions using Python's shutil.copy2 and pathlib.
import shutil
from pathlib import Path
source = Path("sample.txt")
destination = Path("sample_copy.txt")
source.write_text("Hello, PythonSkillset!")
if __name__ == "__main__":
shutil.copy2(source, destination)
copied = destination.read_text()
print(f"Copied content: {copied}")
print(f"Source exists:…
How to Create Nested Directories with pathlib mkdir parents in Python
Create nested directories with pathlib's Path.mkdir using parents=True and exist_ok=True to avoid errors when paths already exist.
from pathlib import Path
def create_nested_directories(base_path: str, dirs: list[str]) -> None:
for directory in dirs:
path = Path(base_path) / directory
path.mkdir(parents=True, exist_ok=True)
print(f"Created: {path}")
if __name__ == "__main__":
root = "output"
nested_dirs = ["2…
How to Extract Text from PDF Files in Python
Extract all readable text from a PDF file using PyPDF2, iterating over each page and concatenating the content.
import PyPDF2
def extract_text_from_pdf(pdf_path):
text = ""
with open(pdf_path, "rb") as file:
reader = PyPDF2.PdfReader(file)
for page in reader.pages:
text += page.extract_text() + "\n"
return text.strip()
if __name__ == "__main__":
pdf_path = "sample.pdf"
extracted…
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.