Reference library

Files & data

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

6 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 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.

pathlib filesystem file-metadata
Python
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()…
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 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 Validate a JSON File in Python

A beginner-friendly Python helper that reads a JSON file, catches common errors, and returns a status dictionary.

json validation file-handling
Python
import json
from pathlib import Path

def get_valid_json_data(file_path: str) -> dict:
    file = Path(file_path)
    if not file.exists():
        return {"status": "error", "message": f"File not found: {file_path}"}
    
    try:
        data = json.loads(file.read_text())
    except json.JSONDecodeError as e:
     …
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.