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 Parse JSON, TXT, and CSV Files in Python
This code provides simple functions to read and parse JSON, text, and CSV files using Python's standard library, returning native data structures.
import json
from pathlib import Path
def parse_json_file(filepath):
"""Read and parse a JSON file, returning its contents."""
path = Path(filepath)
with path.open('r', encoding='utf-8') as f:
return json.load(f)
def parse_txt_lines(filepath):
"""Read a text file and return non-empty stripped …
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.
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__":…
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.