Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
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:
…
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…
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 Handle Missing Values in a CSV Numeric Column in Python
Clean missing entries in a CSV numeric column by filling them with the mean, median, a custom value, or dropping rows.
import csv
from pathlib import Path
import statistics
def clean_csv_numeric(input_path: str, output_path: str, column: str, strategy: str = "mean") -> None:
"""
Handles missing values in a numeric column of a CSV file.
Strategies: 'mean', 'median', 'drop', or 'fill' with a specified value.
"""
row…
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 Sanitize Filenames in Python
Strip illegal filename characters and clean up names for safe filesystem use.
import re
from pathlib import Path
def sanitize_filename(filename: str, replacement: str = "_") -> str:
"""
Remove illegal characters from a filename.
Illegal characters: / \\ : * ? " < > |
Also strips leading/trailing spaces and dots.
"""
# Remove illegal characters
sanitized = re.su…
Read Entire File into String with read Method in Python
Open a file, read its entire content into a string using the .read() method, and clean up with a context manager.
from pathlib import Path
def read_file_to_string(file_path: str) -> str:
"""Read the entire file content into a string using the read method."""
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
return content
if __name__ == "__main__":
# Create a temporary file for d…
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.