Reference library

Files & data

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

20 matches
Files & data easy

Append a Line to a Log File in Python

Append a line to a file using a context manager and Path.open().

file-io logging pathlib
Python
from pathlib import Path

def append_to_log(filepath, message):
    with Path(filepath).open("a") as log_file:
        log_file.write(f"{message}\n")

if __name__ == "__main__":
    log_path = "log.txt"
    append_to_log(log_path, "First entry")
    append_to_log(log_path, "Second entry")
    
    # Verify contents
  …
19 0 Open
Files & data easy

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.

cli json persistence
Python
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…
113 0 Open
Files & data easy

Compress and Extract ZIP Files Programmatically in Python

Create a ZIP archive with in-memory files and extract its contents to a directory using Python's stdlib zipfile and pathlib modules.

zip compression file-io
Python
import zipfile
from pathlib import Path
import tempfile
import os

def create_sample_zip(zip_path: str, files: dict) -> None:
    """Create a ZIP file containing the given files (name -> content mapping)."""
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
        for filename, content in files.ite…
99 0 Open
Files & data easy

File Data Helper Functions in Python

Read and write text and JSON files, and list files in a directory, using pathlib-based helper functions.

file-io pathlib json
Python
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):
…
14 0 Open
Files & data medium

How to Atomically Write Files in Python with Temp File and Rename

Write a file atomically using a temporary file and os.replace so readers never see partial writes even if the process crashes mid-write.

atomic-write tempfile fsync
Python
import os
import tempfile
from pathlib import Path

def atomic_write(path: str | Path, content: str) -> None:
    """Write content to path atomically using a temp file and rename."""
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)

    fd, temp_path = tempfile.mkstemp(
        dir=str(path.par…
17 0 Open
Files & data easy

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.

csv type-conversion file-io
Python
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(…
11 0 Open
Files & data easy

How to Extract Text from PDF Files in Python

Extract all readable text from a PDF file using PyPDF2, iterating over each page and concatenating the content.

pdf text-extraction pypdf2
Python
import PyPDF2

def extract_text_from_pdf(pdf_path):
    text = ""
    with open(pdf_path, "rb") as file:
        reader = PyPDF2.PdfReader(file)
        for page in reader.pages:
            text += page.extract_text() + "\n"
    return text.strip()

if __name__ == "__main__":
    pdf_path = "sample.pdf"
    extracted…
52 0 Open
Files & data easy

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.

csv filter file-io
Python
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…
19 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 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.

json ndjson file-io
Python
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__"…
12 0 Open
Files & data easy

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.

binary file-io hex
Python
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 …
12 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 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.

json file-io dictionary
Python
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…
13 0 Open
Files & data easy

How to Read a TSV File in Python with csv.DictReader

Read a tab-separated (TSV) file into dictionaries using the csv module's DictReader with a tab delimiter.

csv tsv file-io
Python
import csv
from pathlib import Path

data_file = Path("data.tsv")

# Sample TSV content (tab-separated)
sample = """name\tage\tcity
Alice\t30\tNew York
Bob\t25\tLos Angeles
Carol\t35\tChicago
"""
data_file.write_text(sample)

with data_file.open("r", newline="", encoding="utf-8") as f:
    reader = csv.DictReader(f, d…
14 0 Open
Files & data easy

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.

file-io text-files loops
Python
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(…
14 0 Open
Files & data easy

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.

json file-io pathlib
Python
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…
14 0 Open
Files & data easy

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.

file-io pathlib text-files
Python
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__":…
13 0 Open
Files & data easy

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.

bom utf8 pathlib
Python
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")
    …
12 0 Open
Files & data easy

Read Entire File into String with read Method in Python

Open a file, read its entire content into a string using the .read() method, and clean up with a context manager.

file-io read-method context-manager
Python
from pathlib import Path

def read_file_to_string(file_path: str) -> str:
    """Read the entire file content into a string using the read method."""
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    return content

if __name__ == "__main__":
    # Create a temporary file for d…
14 0 Open
Files & data easy

Read an XML File with xml.etree.ElementTree in Python

Parse an XML file and print its root and child elements using the standard library's xml.etree.ElementTree module.

xml elementtree file-io
Python
import xml.etree.ElementTree as ET


def read_xml_file(file_path):
    """Read an XML file and print its structure."""
    tree = ET.parse(file_path)
    root = tree.getroot()
    print(f"Root element: {root.tag}")
    for child in root:
        print(f"Child element: {child.tag}, text: {child.text}")


if __name__ ==…
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.