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.

Easy Python 3.9+ Aug 9, 2026 Files & data 15 views 0 copies

Python code

55 lines
Python 3.9+
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 = Path(filepath)
    with path.open("w", encoding="utf-8") as f:
        json.dump(data, f, indent=2)


def read_text_file(filepath):
    """Read a text file and return content as string."""
    path = Path(filepath)
    return path.read_text(encoding="utf-8")


def write_text_file(filepath, content):
    """Write content to a text file."""
    path = Path(filepath)
    path.write_text(content, encoding="utf-8")


if __name__ == "__main__":
    # Demonstrate with JSON data
    sample_data = {
        "name": "Alice",
        "age": 30,
        "skills": ["Python", "SQL"]
    }

    # Save to file
    file_path = "sample_data.json"
    save_json_file(file_path, sample_data)

    # Load it back
    loaded_data = load_json_file(file_path)
    print("Loaded JSON:", loaded_data)
    print("Name:", loaded_data["name"])

    # Demonstrate with text
    text_file = "notes.txt"
    write_text_file(text_file, "Hello, Python!")
    print("Text file contents:", read_text_file(text_file))

    # Clean up temp files
    Path(file_path).unlink()
    Path(text_file).unlink()

Output

stdout
Loaded JSON: {'name': 'Alice', 'age': 30, 'skills': ['Python', 'SQL']}
Name: Alice
Text file contents: Hello, Python!

How it works

The pathlib.Path class provides an object-oriented way to represent file paths, with methods like open(), read_text(), and write_text() that handle encoding automatically. The json module's load() reads JSON data directly from a file object, while dump() serializes Python data with pretty-printing via the indent=2 parameter. Using with statements ensures files are closed properly even if exceptions occur. The functions wrap these operations into simple helpers that abstract away path management and encoding details.

Common mistakes

  • Forgetting to specify encoding='utf-8' can cause UnicodeDecodeError on files with special characters
  • Writing to a file without creating parent directories causes FileNotFoundError
  • Using json.loads instead of json.load when reading from a file object

Variations

  1. Use json.loads(path.read_text()) for a one-liner when you prefer reading text then parsing
  2. Use open() with a context manager directly without pathlib if you prefer classic file handling

Real-world use cases

  • Persisting application configuration or state between runs, like saving user preferences or session data.
  • Building a simple data export tool that converts internal data structures to shareable JSON or text files.
  • Creating log files or data dumps for debugging, where raw text output needs to be stored for later analysis.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.