Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
Convert Image to ASCII Art in Python
Convert any image to ASCII art by resizing, converting to grayscale, and mapping pixel brightness to characters using Pillow.
from PIL import Image
import sys
ASCII_CHARS = "@%#*+=-:. "
def resize_image(image, new_width=100):
"""Resize image maintaining aspect ratio."""
width, height = image.size
ratio = height / width
new_height = int(new_width * ratio * 0.55) # 0.55 adjusts for font aspect ratio
return image.resize((…
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 Find HTML Elements by Tag, Class, ID, CSS Selector, and Attribute in BeautifulSoup
Parse an HTML string with BeautifulSoup and demonstrate five distinct ways to locate elements: by tag name, by class, by ID, by CSS selector, and by attribute.
from bs4 import BeautifulSoup
html_content = """
<html><body>
<h1 id="title" class="heading">Hello World</h1>
<p class="content">First paragraph</p>
<p class="content special">Second paragraph</p>
<a href="https://example.com" class="link">Click here</a>
<div id="footer">
<p>© 2024</p>
…
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 Load a YAML Subset in Python Without PyYAML
Parse a flat, key-value YAML file with the Python standard library (re and pathlib), handling comments, quotes, and inline comments while skipping nested structures.
import re
from pathlib import Path
def load_yaml_subset(path):
"""Load a flat YAML file (key: value) without external dependencies."""
data = {}
with open(path, 'r', encoding='utf-8') as f:
for line in f:
# Skip empty lines and comments
line = line.strip()
if no…
How to Scrape Headlines from a News Website Using Beautiful Soup in Python
Scrape headline text from a news website using requests and Beautiful Soup with a CSS selector.
import requests
from bs4 import BeautifulSoup
def scrape_headlines(url: str, selector: str) -> list:
"""
Scrape headlines from a news website using Beautiful Soup.
Args:
url: The URL of the news website.
selector: CSS selector for headline elements.
Returns:
List of h…
How to Split Files by Extension in Python
Group files in a folder by their file extension into a dictionary using pathlib.
from pathlib import Path
def split_files_by_extension(folder_path):
folder = Path(folder_path)
files_by_ext = {}
for file_path in folder.iterdir():
if file_path.is_file():
ext = file_path.suffix.lower() or "no_extension"
files_by_ext.setdefault(ext, []).append(file_path.na…
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")
…
Rotate Log Files in Python by Size
This code rotates a log file when its size exceeds a threshold, keeping a specified number of backups.
import os
import glob
from pathlib import Path
def rotate_log(log_path, max_size_bytes=1024, max_backups=3):
log_file = Path(log_path)
if log_file.stat().st_size <= max_size_bytes:
print(f"Log size {log_file.stat().st_size} bytes <= threshold, no rotation")
return
for i in range(max_backu…
Scrape HTML Tables and Convert Them to CSV Using Beautiful Soup in Python
Scrape a Wikipedia table with Beautiful Soup and write the data to a CSV file using the csv module.
import requests
from bs4 import BeautifulSoup
import csv
url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
tables = soup.find_all('table', {'class': 'wikitable'})
if tables:
target_table = tables[2]
rows =…
Sync only changed files between two folders in Python
This code compares two folders and copies only the new or modified files from source to destination, skipping unchanged ones by comparing SHA-256 hashes.
import hashlib
from pathlib import Path
import shutil
def file_hash(path: Path, chunk_size: int = 8192) -> str:
hasher = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
hasher.update(chunk)
return hasher.hexdigest()
def sync_files(src: s…
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.