Reference library

Files & data

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

19 matches
Files & data easy

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.

cli json persistence
Python
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…
113 0 Open
Files & data medium

Build a Secure Local Password Vault with Encrypted Storage in Python

A Python class that stores and retrieves passwords in an encrypted JSON file using Fernet symmetric encryption from the cryptography library.

encryption security passwords
Python
import json
import os
import base64
import hashlib
from cryptography.fernet import Fernet
from getpass import getpass

class PasswordVault:
    def __init__(self, vault_file="vault.json", key_file="vault.key"):
        self.vault_file = vault_file
        self.key_file = key_file
        self.key = self._load_or_creat…
48 0 Open
Files & data easy

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.

etl json jsonl
Python
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…
13 0 Open
Files & data easy

Convert CSV Files to JSON in Python

Convert a CSV file to a JSON file using Python's built-in csv and json modules.

csv json conversion
Python
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:
      …
93 0 Open
Files & data medium

Create a Local File Versioning System Using Pure Python

Track file changes locally by copying versions with SHA-256 hashes and JSON metadata using only the Python standard library.

file-versioning files backup
Python
import os
import shutil
import hashlib
import json
import time
from pathlib import Path

class LocalFileVersioning:
    def __init__(self, target_dir="versioned_files", versions_dir="versions"):
        self.target_dir = Path(target_dir)
        self.versions_dir = Path(versions_dir)
        self.metadata_file = self.…
52 0 Open
Files & data easy

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.

json knowledge base search
Python
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)
    …
54 0 Open
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 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.

api json weather
Python
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…
91 0 Open
Files & data easy

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.

pathlib file-metadata filesystem
Python
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…
12 0 Open
Files & data easy

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.

json files pathlib
Python
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…
11 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 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.

json config pathlib
Python
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…
14 0 Open
Files & data easy

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.

json csv file parsing
Python
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 …
14 0 Open
Files & data easy

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.

json ndjson file-io
Python
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__"…
12 0 Open
Files & data easy

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.

json file-io dictionary
Python
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…
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 Validate JSON Schema Shape in Python

Validate JSON data against a schema using manual checks for required fields, types, and constraints.

json validation schema
Python
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…
12 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
Files & data easy

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.

json files serialization
Python
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…
14 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.