Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
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…
Calculate Working Hours Between Two Dates in Python
Compute total business hours (Mon-Fri, 09:00-17:00) between two datetime objects, excluding weekends and non-working hours.
from datetime import datetime, timedelta
def work_hours_between(start: datetime, end: datetime) -> float:
"""Calculate total working hours between two datetimes (Mon-Fri, 09:00-17:00)."""
def is_workday(d: datetime) -> bool:
return d.weekday() < 5
total_hours = 0.0
current = start
whi…
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…
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…
Find Duplicate Web Pages by Content Similarity in Python
Compute SHA-256 hashes of file contents to detect and report duplicate HTML pages or any files in a directory.
import hashlib
import os
from collections import defaultdict
def get_file_hash(filepath):
"""Compute SHA-256 hash of file contents."""
sha256 = hashlib.sha256()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256.update(chunk)
return sha256.hexdiges…
How to Compute File SHA256 Hash with hashlib in Python
Compute the SHA256 hash of a file by reading it in chunks with hashlib and Path.open.
import hashlib
from pathlib import Path
def sha256_file(file_path: Path) -> str:
sha256_hash = hashlib.sha256()
with file_path.open("rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
sha256_hash.update(chunk)
return sha256_hash.hexdigest()
if __name__ == "__main__":
demo_fi…
How to Merge Sorted Chunk Files in Python
Merge multiple sorted text files into one sorted output file using a heap for efficient k-way merging.
import heapq
def merge_sorted_chunks(chunks, output_path):
"""Merge multiple sorted iterables into single sorted output file."""
with open(output_path, "w") as out_f:
# Open all chunk files
handles = [open(chunk, "r") for chunk in chunks]
try:
# Heap of (value, index) tupl…
Join two CSV files on shared key column in Python
Merge rows from two CSV files by a common key column, outputting combined records to a new file.
import csv
def join_csv(file1, file2, key, output="joined.csv"):
# Read first CSV into dict keyed by the join column
with open(file1, newline="") as f1:
reader1 = csv.DictReader(f1)
data1 = {row[key]: row for row in reader1}
# Read second CSV and merge matching rows
with open(file2, n…
Browse by section
Each section groups closely related Python snippets.
Files & data — Python code examples
What you will find here
This page collects files & data snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.