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…
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 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:
…
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…
Create a Local File Versioning System Using Pure Python
Track file changes locally by copying versions with SHA-256 hashes and JSON metadata using only the Python standard library.
import os
import shutil
import hashlib
import json
import time
from pathlib import Path
class LocalFileVersioning:
def __init__(self, target_dir="versioned_files", versions_dir="versions"):
self.target_dir = Path(target_dir)
self.versions_dir = Path(versions_dir)
self.metadata_file = self.…
Create a ZIP Archive of a Folder in Python
Recursively zip all files in a folder into a single archive using the standard library zipfile and pathlib modules.
import zipfile
from pathlib import Path
def zip_folder(source_dir: str, archive_path: str) -> None:
"""Zip all files in source_dir recursively into archive_path."""
source = Path(source_dir)
with zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED) as archive:
for file_path in source.rglob("*"…
How to Atomically Write Files in Python with Temp File and Rename
Write a file atomically using a temporary file and os.replace so readers never see partial writes even if the process crashes mid-write.
import os
import tempfile
from pathlib import Path
def atomic_write(path: str | Path, content: str) -> None:
"""Write content to path atomically using a temp file and rename."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp_path = tempfile.mkstemp(
dir=str(path.par…
How to Automatically Extract Every Archive in a Folder with Python
Walk through a folder and extract all ZIP, RAR, and 7Z archives into separate subdirectories using Python.
import zipfile
import rarfile
import py7zr
import pathlib
def extract_archives(folder: str):
"""Extract every ZIP, RAR, and 7Z archive in the given folder."""
folder_path = pathlib.Path(folder)
for archive_file in folder_path.iterdir():
suffix = archive_file.suffix.lower()
try:
…
How to Automatically Merge Hundreds of Excel Files Without Losing Formatting in Python
Merge all .xlsx files in a folder into a single Excel workbook, preserving individual sheet structures with sheet name prefixes.
import pandas as pd
from pathlib import Path
def merge_excel_files(folder_path: str, output_path: str) -> None:
"""
Merge all .xlsx files in a folder into a single Excel file,
preserving individual sheet structures.
"""
folder = Path(folder_path)
excel_files = list(folder.glob("*.xlsx"))
…
How to Bulk Insert Rows into SQLite in Python
Insert many rows into an SQLite table in one call with cursor.executemany, then verify them with a SELECT query.
import sqlite3
# Create an in-memory database and a table
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
cursor.execute("CREATE TABLE products (name TEXT, price REAL, quantity INTEGER)")
# Data to insert in bulk
products = [
("Laptop", 999.99, 5),
("Mouse", 19.99, 50),
("Keyboard", 49.99, 30),…
How to Convert CSV Column Types While Reading in Python
Read a CSV file and automatically convert column values to int, float, str, or bool based on type suffixes in the header names.
import csv
from pathlib import Path
from typing import Any
def read_csv_with_types(filepath: str) -> list[dict[str, Any]]:
"""Read CSV and convert column types based on header suffixes."""
converters = {
"int": int,
"float": float,
"str": str,
"bool": lambda v: v.strip().lower(…
How to Detect File Encoding: UTF-8 vs Latin-1 in Python
Detect whether a file is UTF-8 or Latin-1 encoded by attempting a UTF-8 decode and falling back to Latin-1.
import sys
def detect_encoding(file_path):
with open(file_path, 'rb') as f:
raw = f.read()
try:
raw.decode('utf-8')
return 'UTF-8'
except UnicodeDecodeError:
return 'latin1'
if __name__ == "__main__":
file_path = sys.argv[1] if len(sys.argv) > 1 else 'sample.txt'
…
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…
How to Find Files by Extension in Python
This code walks a directory tree with pathlib, collects all file paths, and counts them by extension to summarize a project's contents.
from pathlib import Path
def get_project_files(base_path="."):
"""Return a sorted list of all file paths under base_path."""
base = Path(base_path)
files = [p for p in base.rglob("*") if p.is_file()]
return sorted(files)
def count_by_extension(files):
"""Return a dict mapping extension (lowercase…
How to Generate an Inventory Report of All Files in Python
Walk a directory tree, collect metadata for every file, and write a CSV inventory report using Python's os, pathlib, and csv modules.
import os
import csv
from pathlib import Path
from datetime import datetime
def generate_inventory_report(root_dir: str = "/", output_file: str = "inventory_report.csv"):
headers = ["File Path", "Size (bytes)", "Last Modified", "File Type"]
rows = []
start_time = datetime.now()
for dirpath, dirna…
How to List Files Matching a Glob Pattern in Python
Uses pathlib.Path.glob to find and sort all files matching a glob pattern like *.py in a directory.
from pathlib import Path
def list_files_matching(pattern: str, directory: str = ".") -> list[str]:
"""Return sorted list of file paths matching the glob pattern in a directory."""
return sorted(Path(directory).glob(pattern))
if __name__ == "__main__":
# Example: list all .py files in current directory
…
How to Load Pickle Files Safely in Python
This code demonstrates how to load pickle files safely in Python by using a restricted unpickler that only allows specific, trusted classes, preventing arbitrary code execution from untrusted pickles.
import pickle
# Default pickle.load is unsafe: it executes arbitrary code when unpickling.
class Unsafe:
def __reduce__(self):
return (eval, ("open('/tmp/pickle_demo.txt', 'w').write('pwned')",))
# Create a malicious payload (simulating untrusted source)
malicious_data = pickle.dumps(Unsafe())
# Safe ap…
How to Prune Empty Directories in Python with os.walk
Remove all empty subdirectories bottom-up using os.walk with topdown=False and os.rmdir, safely ignoring non-empty folders.
import os
def prune_empty_dirs(root):
"""Remove all empty subdirectories under root, bottom-up."""
for dirpath, dirnames, filenames in os.walk(root, topdown=False):
if dirpath == root:
continue
try:
os.rmdir(dirpath)
print(f"Removed: {dirpath}")
exce…
How to Strip BOM When Reading UTF-8 Files in Python
Read a UTF-8 text file with Python's pathlib while automatically stripping the Byte Order Mark (BOM) so the first character isn't a hidden glyph.
from pathlib import Path
def read_text_without_bom(file_path):
"""Read a UTF-8 text file, stripping the BOM if present."""
return Path(file_path).read_text(encoding='utf-8-sig')
if __name__ == "__main__":
# Create a sample file with BOM for demonstration
sample_path = Path("sample_with_bom.txt")
…
How to Write a List of Lines to a Text File Safely in Python
This code atomically writes a list of strings as lines to a text file using a temporary file and os.replace to prevent corruption.
from pathlib import Path
import tempfile
import os
def write_lines_safely(lines: list[str], filepath: str | Path) -> None:
"""Write lines to a text file atomically to avoid corruption."""
path = Path(filepath)
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp_path = tempfile.mkstemp(dir=str…
Split CSV Files into Smaller Chunks in Python
Splits a large CSV file into multiple smaller chunk files, preserving the header row in each chunk.
import csv
import os
def split_csv(input_file, chunk_size=1000, output_prefix="chunk"):
"""Split a large CSV file into smaller chunks."""
with open(input_file, 'r', newline='') as infile:
reader = csv.reader(infile)
header = next(reader)
file_count = 1
row_count = 0
…
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.