PyPython · Lesson 10 of 14

File I/O

Python file handling is clean and safe with the "with" statement, which automatically closes files even if an exception occurs. It is a small thing that prevents a large number of subtle bugs.

Python
# Reading files
# open(path, mode) — mode: 'r' read, 'w' write, 'a' append, 'b' binary

# Read entire file
with open("hello.txt", "r") as f:
    content = f.read()
    print(content)

# Read line by line (memory-efficient for large files)
with open("data.txt", "r") as f:
    for line in f:
        print(line.strip())  # strip() removes trailing newline

# Read all lines into a list
with open("data.txt", "r") as f:
    lines = f.readlines()  # each line includes \n
    lines = [l.strip() for l in lines]

# Writing files
with open("output.txt", "w") as f:  # 'w' overwrites!
    f.write("Hello, file!\n")
    f.write("Second line\n")

# Appending
with open("log.txt", "a") as f:
    f.write("New log entry\n")

# Writing multiple lines at once
lines = ["line 1\n", "line 2\n", "line 3\n"]
with open("output.txt", "w") as f:
    f.writelines(lines)
Python
import json
import csv
from pathlib import Path

# JSON
data = {"name": "Alice", "scores": [95, 87, 92], "active": True}

# Write JSON
with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

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

# CSV
rows = [
    ["name", "age", "city"],
    ["Alice", "30", "Paris"],
    ["Bob", "25", "Berlin"],
]

with open("people.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

with open("people.csv", "r") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(f"{row['name']} lives in {row['city']}")

# pathlib — modern path handling
p = Path("data")
p.mkdir(exist_ok=True)         # create directory
(p / "file.txt").write_text("hello")   # write
text = (p / "file.txt").read_text()    # read
print(list(p.glob("*.txt")))   # find files
print(p.exists())              # True
⚠ Warning
Always use "with open(...) as f:" — never bare open() without a close(). The with statement guarantees the file is closed even if an exception is raised inside the block. Also: "w" mode truncates the file immediately on open, before you write anything.