Reference library

Files & data

Read and write files safely; parse JSON, CSV, and common text formats.

9 matches
Files & data medium

Build a Personal Work Hours Tracker in Python

A Python class that logs daily work hours to a CSV file and produces a weekly summary of total hours worked.

work-hours time-tracking csv
Python
import csv
from pathlib import Path
from datetime import datetime, date

class WorkHoursTracker:
    def __init__(self, file_path="work_hours.csv"):
        self.file_path = Path(file_path)
        if not self.file_path.exists():
            with open(self.file_path, "w", newline="") as f:
                writer = csv…
60 0 Open
Files & data easy

Generate Timesheet Reports from Daily Logs in Python

Aggregate daily log entries by project and produce a formatted timesheet report using Python's standard library.

timesheet reporting aggregation
Python
import json
from pathlib import Path
from collections import defaultdict

def generate_timesheet_report(daily_logs: list[dict]) -> str:
    """
    Generate a timesheet report from daily log entries.
    
    Args:
        daily_logs: List of dicts with 'date', 'project', 'hours', 'task' keys
    
    Returns:
       …
45 0 Open
Files & data medium

Generate a Monthly Calendar PDF in Python

Create a Python utility that generates a monthly calendar PDF using ReportLab, with weekday headers and day numbers laid out in a grid.

calendar pdf reportlab
Python
from calendar import TextCalendar
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import os

def generate_monthly_calendar_pdf(year, month, filename="calendar.pdf"):
    cal = TextCalendar()
    days = cal.monthdays2calendar(year, month)
    
    month_name …
1767 0 Open
Files & data easy

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.

pathlib filesystem filtering
Python
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…
13 0 Open
Files & data medium

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.

mmap file-io memory-efficient
Python
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…
12 0 Open
Files & data easy

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.

json dict merge
Python
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,…
13 0 Open
Files & data easy

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.

file-io retry error-handling
Python
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…
14 0 Open
Files & data easy

How to Validate JSON Schema Shape in Python

Validate JSON data against a schema using manual checks for required fields, types, and constraints.

json validation schema
Python
import json
from typing import Any, Dict

def validate_person_schema(data: Dict[str, Any]) -> bool:
    """Validate a person object against expected schema shape."""
    if not isinstance(data, dict):
        return False
    
    # Required fields check
    required_fields = {"name", "age", "email"}
    if not requir…
12 0 Open
Files & data medium

Tail last N lines of growing log file in Python

Prints the last n lines of a log file and follows new content appended to it, polling for size changes.

log-file file-handling polling
Python
import time
from pathlib import Path

def tail_log(file_path, n=10, poll_interval=1.0, timeout=10):
    """
    Print the last n lines and follow new lines appended to a growing log file.
    """
    path = Path(file_path)
    # Read the last n lines from the current file
    with path.open("r", encoding="utf-8") as f…
12 0 Open

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.