Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
How to Extract IP Address Counts from Access Logs in Python
Read a web server access log, count occurrences of each IP address using regex and Counter, and print the ranked results.
import re
from collections import Counter
from pathlib import Path
def extract_ip_counts(log_file_path):
ip_pattern = r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
ip_counter = Counter()
with open(log_file_path, 'r') as file:
for line in file:
match = re.match(ip_pattern, line)
…
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 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…
Normalize CSV Column Names to snake_case in Python
Convert CSV header names to snake_case using a regular expression and write the updated file in place.
import csv
import re
import sys
def to_snake_case(header):
header = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", header)
header = re.sub(r"[^a-zA-Z0-9]+", "_", header).strip("_").lower()
return header
def normalize_csv_headers(input_path, output_path=None):
with open(input_path, newline="", encoding="utf…
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.