Skip to content

Chapter 8: File Operations

Reading and Writing Text Files

bash
# Use with statement (recommended! automatically closes file)
# Write to file
with open("hello.txt", "w", encoding="utf-8") as f:
    f.write("Hello, Python!\n")
    f.write("Second line\n")
    f.write("Third line\n")

print("File written successfully!")

# Read entire file
with open("hello.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(f"--- Full file contents ---")
    print(content)

# Read line by line (suitable for large files)
with open("hello.txt", "r", encoding="utf-8") as f:
    print("--- Reading line by line ---")
    for line_num, line in enumerate(f, 1):
        print(f"Line {line_num}: {line.strip()}")
bash
File written successfully!
--- Full file contents ---
Hello, Python!
Second line
Third line

--- Reading line by line ---
Line 1: Hello, Python!
Line 2: Second line
Line 3: Third line

📝 Note: 📝 File open modes: "r" read-only (default), "w" write (overwrites), "a" append, "r+" read-write, "rb" binary read.

Working with JSON Files

bash
import json

# Python dict → JSON file
data = {
    "students": [
        {"name": "Alice", "age": 18, "scores": [85, 92, 78]},
        {"name": "Bob", "age": 17, "scores": [90, 95, 88]},
        {"name": "Charlie", "age": 19, "scores": [70, 65, 80]}
    ],
    "class": "Class 2, Year 3"
}

with open("students.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

print("JSON file saved!")

# JSON file → Python dict
with open("students.json", "r", encoding="utf-8") as f:
    loaded = json.load(f)

for student in loaded["students"]:
    avg = sum(student["scores"]) / len(student["scores"])
    print(f"  {student['name']}: average score {avg:.1f}")
bash
JSON file saved!
  Alice: average score 85.0
  Bob: average score 91.0
  Charlie: average score 71.7

Working with CSV Files

bash
import csv

# Write CSV
with open("employees.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Department", "Salary"])
    writer.writerow(["Alice", "Engineering", 15000])
    writer.writerow(["Bob", "Marketing", 12000])
    writer.writerow(["Charlie", "Engineering", 18000])

# Read CSV
with open("employees.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    print("Employee info:")
    for row in reader:
        print(f"  {row['Name']} | {row['Department']} | ${row['Salary']}")
bash
Employee info:
  Alice | Engineering | $15000
  Bob | Marketing | $12000
  Charlie | Engineering | $18000