Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
How to Audit Environment Variable Files for Missing Values in Python
A Python tool that reads an environment variable file and reports any variables with empty or missing values.
import os
import re
from pathlib import Path
def audit_env_file(filepath: str) -> None:
"""
Audit an environment variable file for missing values.
Prints file status and lists variables that have empty values.
"""
path = Path(filepath)
if not path.exists():
print(f"Error: File '{filepa…
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 Build a CSV Comparison Tool That Highlights Every Changed Cell in Python
Read two CSV files with DictReader, compare cell by cell, and return a list of dictionaries describing each changed cell using only the standard library.
import csv
from pathlib import Path
def csv_cell_diff(file_a: str, file_b: str) -> list[dict]:
rows_a = list(csv.DictReader(Path(file_a).open('r', newline='')))
rows_b = list(csv.DictReader(Path(file_b).open('r', newline='')))
if not rows_a or not rows_b:
return []
columns = list(rows_a[0].key…
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 Compare Two Files by Content Hash Equality in Python
Compares two files by hashing their contents with SHA-256, skipping the hash if file sizes differ, and returns whether they are identical.
import hashlib
from pathlib import Path
def file_hash(path: Path, chunk_size: int = 8192) -> str:
sha256 = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
sha256.update(chunk)
return sha256.hexdigest()
def files_are_identical(file_a: Pat…
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…
How to Filter Files by Extension and Size in Python
Use pathlib to list files in a directory, filter by extension or minimum size, and return matching names or (name, size) pairs.
from pathlib import Path
def filter_files_by_extension(directory: str, extension: str) -> list:
"""Return a list of file names in directory with the given extension."""
path = Path(directory)
return [f.name for f in path.iterdir() if f.is_file() and f.suffix == extension]
def filter_files_by_size(directo…
How to Find Duplicate Files by Size and Hash in Python
Recursively scan a directory, group files by size, then hash candidates to identify exact duplicate files.
import hashlib
from pathlib import Path
def hash_file(path, chunk_size=8192):
hasher = hashlib.md5()
with open(path, 'rb') as f:
while chunk := f.read(chunk_size):
hasher.update(chunk)
return hasher.hexdigest()
def find_duplicates(directory):
size_map = {}
for path in Path(dir…
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 Group Files by Extension in Python
Group file names by their file extension using a dictionary and pathlib, producing a simple clear mapping for beginners.
from pathlib import Path
def group_data_by_extension(files: list[Path]) -> dict[str, list[str]]:
"""Group file names by their extension."""
grouped: dict[str, list[str]] = {}
for file in files:
ext = file.suffix.lower()
grouped.setdefault(ext, []).append(file.name)
return grouped
if…
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 List File Information in a Directory with Python
A helper that walks a directory and returns each file's name, size, and extension as a list of dictionaries.
from pathlib import Path
def get_files_data(directory: str) -> list[dict]:
"""Return basic info about all files in a directory."""
files = []
for path in Path(directory).iterdir():
if path.is_file():
files.append({
"name": path.name,
"size": path.stat()…
How to List File Metadata in Python
This code walks a directory and returns a list of JSON-ready dicts with each file's name, size, and modification time.
from pathlib import Path
import json
def format_files_data(directory_path):
"""Return a list of JSON-serializable dicts with file metadata."""
base = Path(directory_path)
if not base.is_dir():
raise ValueError(f"Not a directory: {directory_path}")
files_data = []
for file_path in base.ite…
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 List Tar Archive Contents in Python
Open a tar archive with the stdlib tarfile module and print each entry's type, size, and name.
import tarfile
from pathlib import Path
def list_tar_contents(archive_path):
"""List all entries in a tar archive."""
entries = []
with tarfile.open(archive_path, "r") as tar:
for member in tar.getmembers():
entry_type = "dir" if member.isdir() else "file"
entries.append(f"…
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 Load and Save JSON Files in Python
Load and save JSON files with pretty formatting using Python's standard library json module and pathlib.
import json
from pathlib import Path
def load_json(filepath: str) -> dict:
"""Load JSON data from a file."""
path = Path(filepath)
with path.open("r", encoding="utf-8") as f:
return json.load(f)
def save_json(filepath: str, data: dict) -> None:
"""Save data to a JSON file with pretty format…
How to Memory Map Large Files Read-Only in Python
This code demonstrates reading only the tail of a large file using a read-only memory map (mmap) to avoid loading the entire file into memory.
import mmap
import os
def read_tail_with_mmap(filepath, bytes_from_end=64):
"""Read the last bytes of a large file using a read-only mmap."""
file_size = os.path.getsize(filepath)
start = max(0, file_size - bytes_from_end)
with open(filepath, "rb") as f:
with mmap.mmap(f.fileno(), length=0, a…
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.