Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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 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 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 Merge Dicts from Two JSON Files Like a Pro
This helper reads two JSON files that contain dicts, merges them with the second file overriding duplicate keys, and saves the result to a new file.
import json
from pathlib import Path
def merge_json_files(file1: str, file2: str, output: str = "merged.json") -> dict:
"""Merge two JSON files containing dicts, with file2 overriding file1."""
data1 = json.loads(Path(file1).read_text())
data2 = json.loads(Path(file2).read_text())
merged = {**data1,…
How to Merge Environment-Specific Config JSON in Python
Loads a base JSON config and overlays environment-specific overrides, merging the two dictionaries into one final config.
import json
import pathlib
def load_config(base_path: pathlib.Path, env: str) -> dict:
base_config = json.loads(base_path.read_text())
env_path = base_path.with_name(f"config.{env}.json")
if env_path.exists():
env_config = json.loads(env_path.read_text())
return {**base_config, **env_conf…
How to Parse INI Config Files in Python with configparser
Load and read settings from an INI file using Python's built-in configparser module, with type-safe value access.
import configparser
from pathlib import Path
# Create a sample INI file for demonstration
sample_content = """
[Database]
host = localhost
port = 5432
user = admin
password = secret123
[Logging]
level = INFO
file = app.log
max_size = 10MB
"""
config_file = Path("sample_config.ini")
config_file.write_text(sample_con…
How to Parse JSON, TXT, and CSV Files in Python
This code provides simple functions to read and parse JSON, text, and CSV files using Python's standard library, returning native data structures.
import json
from pathlib import Path
def parse_json_file(filepath):
"""Read and parse a JSON file, returning its contents."""
path = Path(filepath)
with path.open('r', encoding='utf-8') as f:
return json.load(f)
def parse_txt_lines(filepath):
"""Read a text file and return non-empty stripped …
How to Parse Path Components with pathlib Path in Python
Parse a file path into parent directory, filename, stem, suffix, and parts using the standard library pathlib module.
from pathlib import Path
if __name__ == "__main__":
p = Path("data/reports/2024/final.txt")
print(f"Path: {p}")
print(f"Parent: {p.parent}")
print(f"Name: {p.name}")
print(f"Stem: {p.stem}")
print(f"Suffix: {p.suffix}")
print(f"Parts: {p.parts}")
print(f"Anchor: {p.anchor}")
print(…
How to Read Binary File Bytes and Inspect the Header in Python
Read the first bytes of a binary file with pathlib and display them as a hex dump plus an ASCII view to inspect file headers.
import pathlib
def inspect_binary_header(filepath: str, num_bytes: int = 16) -> None:
"""Read the first bytes of a binary file and display them as hex and ASCII."""
path = pathlib.Path(filepath)
data = path.read_bytes()[:num_bytes]
hex_str = ' '.join(f"{byte:02x}" for byte in data)
ascii_str …
How to Read a File with Retry on Temporary IOError in Python
Read a file with automatic retries on temporary IOError/OSError failures, using the pathlib module with configurable attempts and delay.
import time
from pathlib import Path
def read_file_with_retry(filepath: str | Path, max_attempts: int = 3, delay: float = 0.5) -> str:
"""Read a file with retries on temporary IO errors."""
path = Path(filepath)
last_error = None
for attempt in range(max_attempts):
try:
return pat…
How to Read a JSON File into a Dictionary in Python
Load a JSON file into a Python dictionary using the json.load() function with proper file handling and UTF-8 encoding.
import json
from pathlib import Path
def read_json_file(filepath: str) -> dict:
"""Read a JSON file and return its contents as a dictionary."""
path = Path(filepath)
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
return data
if __name__ == "__main__":
# Create a sample JS…
How to Read a Text File Line by Line in Python
Reads a text file line by line with an enumerated for loop and prints each line number and content.
from pathlib import Path
def read_lines(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
for line_number, line in enumerate(file, start=1):
print(f"Line {line_number}: {line.rstrip()}")
if __name__ == "__main__":
sample_file = Path("sample.txt")
sample_file.write_text(…
How to Read and Write Files in Python (JSON + Text)
A beginner-friendly helper module to read and write JSON and text files using Python's pathlib and json standard library modules.
import json
from pathlib import Path
def load_json_file(filepath):
"""Load data from a JSON file and return as dict/list."""
path = Path(filepath)
with path.open("r", encoding="utf-8") as f:
return json.load(f)
def save_json_file(filepath, data):
"""Save data to a JSON file."""
path = P…
How to Read and Write Text Files in Python
This code provides simple helper functions to save and load text files using Python's standard pathlib library.
from pathlib import Path
def save_text_data(filename: str, content: str) -> None:
file_path = Path(filename)
file_path.write_text(content, encoding="utf-8")
def load_text_data(filename: str) -> str:
file_path = Path(filename)
return file_path.read_text(encoding="utf-8")
if __name__ == "__main__":…
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…
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")
…
How to Sync Two Folders in Python (Lightweight Backup)
A Python script that synchronizes a source folder to a destination folder, copying new or updated files and removing files that no longer exist in the source.
import os
import shutil
import sys
from pathlib import Path
def sync_folders(src: Path, dst: Path):
"""Sync src folder to dst folder, copying missing/updated files."""
dst.mkdir(parents=True, exist_ok=True)
for src_path in src.rglob("*"):
relative = src_path.relative_to(src)
dst_path = ds…
How to Transcode a File from Latin-1 to UTF-8 in Python
Read a latin1-encoded text file and rewrite it as UTF-8 using Python's pathlib and encoding parameters.
from pathlib import Path
def transcode_to_utf8(input_path, output_path):
"""Read a latin1-encoded file and write it as UTF-8."""
source = Path(input_path)
target = Path(output_path)
with source.open(encoding='latin1') as infile:
content = infile.read()
with target.open('w', encod…
How to Watch a Directory for New Files in Python
Poll a directory at regular intervals and detect newly added files, printing each one as it appears.
import time
import os
from pathlib import Path
WATCH_DIR = Path("watched_files")
def watch_for_new_files(directory: Path, sleep_time: float = 1.0, max_iterations: int = 10):
"""Poll a directory for new files and print when one appears."""
directory.mkdir(exist_ok=True)
existing = set(os.listdir(directory…
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…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
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.