Intermediate

File I/O

Learn to read and write files, use context managers, work with CSV and JSON data, and handle errors gracefully.

Reading Files

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

# Read line by line
with open("data.txt", "r") as f:
    for line in f:
        print(line.strip())

# Read single line
with open("data.txt", "r") as f:
    first_line = f.readline()

# Read all lines into a list
with open("data.txt", "r") as f:
    lines = f.readlines()  # List of strings

Writing Files

Python
# Write (creates or overwrites)
with open("output.txt", "w") as f:
    f.write("Hello, World!\n")
    f.write("Second line.\n")

# Append (adds to existing file)
with open("output.txt", "a") as f:
    f.write("Appended line.\n")

# Write multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
    f.writelines(lines)

Context Manager (with Statement)

Always use with to open files. It automatically closes the file when the block exits, even if an exception occurs. This prevents resource leaks and is considered best practice.
ModeDescription
"r"Read (default) — file must exist
"w"Write — creates or truncates file
"a"Append — adds to end of file
"x"Exclusive create — fails if file exists
"rb"Read binary
"wb"Write binary

CSV Files

Python
import csv

# Reading CSV
with open("data.csv", "r") as f:
    reader = csv.reader(f)
    header = next(reader)  # Skip header row
    for row in reader:
        print(row)  # Each row is a list

# Reading CSV as dictionaries
with open("data.csv", "r") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["age"])

# Writing CSV
with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "age", "city"])
    writer.writerow(["Alice", 30, "NYC"])
    writer.writerow(["Bob", 25, "LA"])

JSON Files

Python
import json

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

# Writing JSON
data = {"name": "Alice", "scores": [95, 87, 92]}
with open("output.json", "w") as f:
    json.dump(data, f, indent=2)

# Convert between JSON strings and Python objects
json_str = json.dumps(data)           # Dict to JSON string
parsed = json.loads(json_str)          # JSON string to dict

Exception Handling

Python
try:
    with open("missing.txt", "r") as f:
        content = f.read()
except FileNotFoundError:
    print("File not found!")
except PermissionError:
    print("No permission to read file!")
except Exception as e:
    print(f"Unexpected error: {e}")
else:
    print("File read successfully!")
finally:
    print("This always runs.")

# Raising exceptions
def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero!")
    return a / b

Common File Operations

Python
import os
from pathlib import Path

# Check if file exists
print(os.path.exists("data.txt"))
print(Path("data.txt").exists())

# Get file size
size = os.path.getsize("data.txt")

# List directory contents
files = os.listdir(".")

# Create directories
os.makedirs("output/subdir", exist_ok=True)

# Modern pathlib approach
p = Path("data") / "output.txt"
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("Hello from pathlib!")
content = p.read_text()
💡
Modern Python: Prefer pathlib.Path over os.path for new code. It provides an object-oriented interface that is more readable and cross-platform.