Reference library

Files & data

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

2 matches
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 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

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.