stackademic

The leading education platform for anyone with an interest in software development.

File I/O

Read and write text and binary files with open, paths, and JSON

Overview

Python reads and writes files through file objects returned by open(). Always close files—or prefer context managers—to release system handles. The pathlib module offers a modern path API.

Syntax / Usage

from pathlib import Path

# Text read/write (context manager recommended)
with open("notes.txt", "r", encoding="utf-8") as f:
    content = f.read()

with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Hello\n")

# Line by line
with open("data.csv") as f:
    for line in f:
        print(line.strip())

# pathlib
path = Path("logs/app.log")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("started", encoding="utf-8")
text = path.read_text(encoding="utf-8")

# JSON
import json
data = json.loads(path.read_text())
path.write_text(json.dumps(data, indent=2))

Modes: r read, w write (truncate), a append, rb/wb binary.

Examples

Append a timestamped log entry:

from datetime import datetime
from pathlib import Path

log = Path("app.log")
entry = f"{datetime.now().isoformat()} - Server started\n"
with log.open("a", encoding="utf-8") as f:
    f.write(entry)

Load configuration safely:

import json
from pathlib import Path

config_path = Path("config.json")
if config_path.exists():
    config = json.loads(config_path.read_text())
else:
    config = {"debug": False}

Common Mistakes

  • Omitting encoding="utf-8" and getting platform-dependent defaults on Windows
  • Using read() on huge files—iterate line by line instead
  • Forgetting that "w" overwrites existing files without warning
  • Not handling FileNotFoundError when paths are user-supplied

See Also

python-exceptions python-context-managers python-modules