⚡IntermediatePython in Practice

File I/O

Reading and writing files with open(), context managers, pathlib, and working with CSV and JSON files.

Overview

Working with files is one of the most common tasks in Python. The built-in `open()` function returns a file object you can read from or write to. Always use the `with` statement (context manager) it automatically closes the file when the block exits, even if an exception occurs. File modes: `'r'` (read, default), `'w'` (write truncates), `'a'` (append), `'x'` (create fails if exists), `'b'` suffix for binary mode (`'rb'`, `'wb'`). For reading: `read()` gets the entire file as a string, `readline()` gets one line, and iterating the file object gives lines one at a time (memory-efficient for large files). **pathlib.Path** (Python 3.4+) is the modern, object-oriented approach to file paths cross-platform, composable with `/` operator, and has methods for common operations. The **csv** and **json** modules make structured data trivial.

Key Points

  • •Always use `with open(path, mode) as f:` auto-closes, even on exceptions
  • •Read modes: `r` text, `rb` binary; write modes: `w` (truncate), `a` (append), `x` (exclusive create)
  • •Iterate the file object for lines: `for line in f:` memory-efficient for large files
  • •pathlib.Path: `Path("dir") / "file.txt"` builds paths cross-platform
  • •`Path.read_text()` / `Path.write_text()` read/write without explicit open()
  • •`json.dump(obj, f)` writes JSON to a file; `json.load(f)` parses it back
  • •`csv.reader` and `csv.DictReader` handle CSV files cleanly

Examples

Reading and writing text files

# Writing a file
with open("notes.txt", "w") as f:
    f.write("Line 1\n")
    f.write("Line 2\n")
    f.writelines(["Line 3\n", "Line 4\n"])

# Reading the entire file
with open("notes.txt", "r") as f:
    content = f.read()
    print(content)

# Reading line by line (memory-efficient)
with open("notes.txt") as f:
    for line in f:
        print(line.rstrip())   # rstrip removes trailing \n

# Appending to a file
with open("notes.txt", "a") as f:
    f.write("Line 5\n")

pathlib modern file system operations

from pathlib import Path

# Build paths cross-platform
base = Path("data")
config = base / "config" / "settings.json"
print(config)   # data/config/settings.json

# Quick read/write
p = Path("hello.txt")
p.write_text("Hello, pathlib!")
print(p.read_text())   # Hello, pathlib!

# Check existence, list files
print(p.exists())      # True
print(p.suffix)        # .txt
print(p.stem)          # hello

# List all .txt files in a directory
for txt_file in Path(".").glob("*.txt"):
    print(txt_file.name)

JSON and CSV files

import json, csv
from pathlib import Path

# JSON write and read
data = {"name": "Alice", "scores": [95, 82, 91]}
Path("data.json").write_text(json.dumps(data, indent=2))

with open("data.json") as f:
    loaded = json.load(f)
print(loaded["name"])   # Alice

# CSV write rows and read back
rows = [["Name", "Age"], ["Alice", 30], ["Bob", 25]]
with open("people.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

with open("people.csv") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["Name"], row["Age"])

Common Mistakes

  • Opening a file without `with` if an exception occurs, the file handle leaks and data may not be flushed
  • Using mode `"w"` when you mean `"a"` `"w"` truncates (erases) the file if it already exists
  • Forgetting `newline=""` when writing CSV on Windows causes double newlines in the output

Note

Prefer `Path.read_text()` and `Path.write_text()` for simple single-chunk reads/writes they handle open/close automatically and are more concise than `with open()`. Use `with open()` when you need streaming (line-by-line) access.

Exercises

Write Python code to solve each exercise. Run it in your browser and check your output.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

Why should you use `with open(...) as f:` instead of `f = open(...); ...; f.close()`?