Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
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.
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…
Build a Simple ETL Pipeline in Python
A simple ETL pipeline that reads JSON Lines, transforms records with filtering and normalization, and writes the result to JSON.
import json
from pathlib import Path
def read_input(file_path: Path) -> list[dict]:
"""Read JSON lines file into list of dicts."""
with file_path.open("r", encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
def transform(records: list[dict]) -> list[dict]:
"""Transf…
Convert CSV Files to JSON in Python
Convert a CSV file to a JSON file using Python's built-in csv and json modules.
import csv
import json
def csv_to_json(csv_filepath, json_filepath):
"""Convert a CSV file to a JSON file."""
with open(csv_filepath, mode='r', newline='') as csv_file:
reader = csv.DictReader(csv_file)
data = [row for row in reader]
with open(json_filepath, mode='w') as json_file:
…
Create a Personal Knowledge Base That Searches Notes Instantly in Python
Build a lightweight personal knowledge base with JSON storage and instant case-insensitive full-text search across note titles and content.
import json
import re
import sys
class PersonalKnowledgeBase:
def __init__(self, file_path="kb_notes.json"):
self.file_path = file_path
self.notes = self._load_notes()
def _load_notes(self):
try:
with open(self.file_path, "r") as f:
return json.load(f)
…
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 Fetch Weather Data from a Public API in Python
Fetches and parses weather data from a free public API using only the Python standard library.
import urllib.request
import json
def get_weather(city):
base_url = f"https://wttr.in/{city}?format=j1"
with urllib.request.urlopen(base_url) as response:
data = json.loads(response.read().decode())
current = data["current_condition"][0]
temp = current["temp_C"]
desc = current["weatherDesc…
How to List File Metadata in Python
This code walks a directory and returns a list of JSON-ready dicts with each file's name, size, and modification time.
from pathlib import Path
import json
def format_files_data(directory_path):
"""Return a list of JSON-serializable dicts with file metadata."""
base = Path(directory_path)
if not base.is_dir():
raise ValueError(f"Not a directory: {directory_path}")
files_data = []
for file_path in base.ite…
How to Load and Save JSON Files in Python
Load and save JSON files with pretty formatting using Python's standard library json module and pathlib.
import json
from pathlib import Path
def load_json(filepath: str) -> dict:
"""Load JSON data from a file."""
path = Path(filepath)
with path.open("r", encoding="utf-8") as f:
return json.load(f)
def save_json(filepath: str, data: dict) -> None:
"""Save data to a JSON file with pretty format…
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.
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,…
How to Merge Environment-Specific Config JSON in Python
Loads a base JSON config and overlays environment-specific overrides, merging the two dictionaries into one final config.
import json
import pathlib
def load_config(base_path: pathlib.Path, env: str) -> dict:
base_config = json.loads(base_path.read_text())
env_path = base_path.with_name(f"config.{env}.json")
if env_path.exists():
env_config = json.loads(env_path.read_text())
return {**base_config, **env_conf…
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 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.
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__"…
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.
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…
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…
How to Validate JSON Schema Shape in Python
Validate JSON data against a schema using manual checks for required fields, types, and constraints.
import json
from typing import Any, Dict
def validate_person_schema(data: Dict[str, Any]) -> bool:
"""Validate a person object against expected schema shape."""
if not isinstance(data, dict):
return False
# Required fields check
required_fields = {"name", "age", "email"}
if not requir…
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.
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:
…
How to Write a Dict to a Pretty JSON File with Indent in Python
Serializes a Python dictionary to a readable JSON file using json.dump with indentation and sorted keys, then prints the file contents to stdout.
import json
from pathlib import Path
data = {
"name": "Python",
"version": 3.12,
"features": ["simple", "readable", "powerful"],
"nested": {"creator": "Guido van Rossum", "year": 1991}
}
output_path = Path("output.json")
with output_path.open("w", encoding="utf-8") as f:
json.dump(data, f, inden…
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.