Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
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 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.
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…
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.