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 Command-Line To-Do List Application with Data Persistence in Python
A persistent command-line to-do list that saves tasks as JSON, supporting add, show, toggle done, and quit commands.
import json
import os
TODO_FILE = "todos.json"
def load_todos():
if not os.path.exists(TODO_FILE):
return []
with open(TODO_FILE, "r") as f:
return json.load(f)
def save_todos(todos):
with open(TODO_FILE, "w") as f:
json.dump(todos, f, indent=2)
def show_todos(todos):
if not…
Build a Simple ETL Pipeline in Python
A simple ETL pipeline that reads JSON Lines, transforms records with filtering and normalization, and writes the result to JSON.
import json
from pathlib import Path
def read_input(file_path: Path) -> list[dict]:
"""Read JSON lines file into list of dicts."""
with file_path.open("r", encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
def transform(records: list[dict]) -> list[dict]:
"""Transf…
Convert File Data to a Dictionary in Python
This function scans a directory and converts each file's metadata (name, size, extension) into a structured dictionary for easy access.
from pathlib import Path
def convert_files_data(directory: str) -> dict:
data = {}
base = Path(directory)
if not base.exists():
return data
for file in base.iterdir():
if file.is_file():
data[file.name] = {
"size": file.stat().st_size,
"exten…
Create a Local File Versioning System Using Pure Python
Track file changes locally by copying versions with SHA-256 hashes and JSON metadata using only the Python standard library.
import os
import shutil
import hashlib
import json
import time
from pathlib import Path
class LocalFileVersioning:
def __init__(self, target_dir="versioned_files", versions_dir="versions"):
self.target_dir = Path(target_dir)
self.versions_dir = Path(versions_dir)
self.metadata_file = self.…
Create a Python Tool That Generates Professional Excel Dashboards
Generate a professional sales dashboard in an Excel workbook with styled headers, a bar chart, and formatted number cells using the openpyxl library.
import openpyxl
from openpyxl.chart import BarChart, Reference
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
def create_sales_dashboard(workbook_path: str) -> None:
"""Generate a professional sales dashboard in an Excel workbook."""
wb = op…
Create an In-Memory SQLite Table and Query It in Python
This code creates an in-memory SQLite database, defines an employees table, inserts sample rows, and runs a filtered query with sorted results.
import sqlite3
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
department TEXT NOT NULL,
salary REAL
)
""")
employees = [
(1, "Alice", "Engineering", 95000),
(2, "Bob", "…
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…
Export List of Dicts to CSV in Python
Write a list of dictionaries (dataframe-like) to a CSV file with headers using the standard library csv module and verify by reading it back.
import csv
def export_to_csv(data, filename):
"""Export a list of dicts to a CSV file."""
if not data:
print("No data to export")
return
# Get column names from the keys of the first dict
fieldnames = list(data[0].keys())
with open(filename, 'w', newline='', encoding='utf…
Export SQLite Query Results to CSV in Python
Connects to a SQLite database, runs a query, and writes the result rows and column headers to a CSV file using the standard library.
import sqlite3
import csv
def export_query_to_csv(db_path, query, csv_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute(query)
rows = cursor.fetchall()
column_names = [description[0] for description in cursor.description]
with open(csv_path, 'w', newline='', encodi…
File Data Helper Functions in Python
Read and write text and JSON files, and list files in a directory, using pathlib-based helper functions.
from pathlib import Path
def load_text_file(filepath):
"""Read a text file and return its contents as a string."""
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not found: {filepath}")
return path.read_text(encoding="utf-8")
def save_text_file(filepath, content):
…
How to Bulk Insert Rows into SQLite in Python
Insert many rows into an SQLite table in one call with cursor.executemany, then verify them with a SELECT query.
import sqlite3
# Create an in-memory database and a table
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
cursor.execute("CREATE TABLE products (name TEXT, price REAL, quantity INTEGER)")
# Data to insert in bulk
products = [
("Laptop", 999.99, 5),
("Mouse", 19.99, 50),
("Keyboard", 49.99, 30),…
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 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 Fetch Weather Data from a Public API in Python
Fetches and parses weather data from a free public API using only the Python standard library.
import urllib.request
import json
def get_weather(city):
base_url = f"https://wttr.in/{city}?format=j1"
with urllib.request.urlopen(base_url) as response:
data = json.loads(response.read().decode())
current = data["current_condition"][0]
temp = current["temp_C"]
desc = current["weatherDesc…
How to Filter CSV Rows by Column Value in Python
Filter CSV rows based on a column value condition using the standard csv module and a lambda function.
import csv
def filter_csv(input_file, output_file, column, condition):
with open(input_file, newline='', encoding='utf-8') as infile, \
open(output_file, 'w', newline='', encoding='utf-8') as outfile:
reader = csv.DictReader(infile)
fieldnames = reader.fieldnames
writer = csv.Dict…
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 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 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 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 NDJSON Lines into a List in Python
Reads a JSON-lines (NDJSON) file line by line and converts each non-empty line into a Python object, returning a list.
import json
from pathlib import Path
def parse_ndjson(file_path: str) -> list:
data = []
with Path(file_path).open("r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
data.append(json.loads(line))
return data
if __name__ == "__main__"…
How to Sum a CSV Column by Group in Python
This code reads a CSV string and sums a specified column for each unique value of a group key using the csv module and defaultdict.
import csv
from collections import defaultdict
from io import StringIO
def aggregate_csv(csv_data, group_key, sum_column):
totals = defaultdict(float)
reader = csv.DictReader(StringIO(csv_data))
for row in reader:
key = row[group_key]
totals[key] += float(row[sum_column])
return dict(t…
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.