Learn Without Walls
← Back to Module 11

Module 11: Quick Reference

File Handling Cheat Sheet

File Modes

ModeDescriptionFile ExistsFile Missing
"r"Read (default)OpensError
"w"Write (overwrites)Erases contentCreates
"a"AppendAdds to endCreates
"x"Exclusive createErrorCreates

Reading Files

with open("file.txt", "r") as f:
    content = f.read()        # Entire file as string
    line = f.readline()       # One line at a time
    lines = f.readlines()     # All lines as list

# Best: iterate directly
with open("file.txt") as f:
    for line in f:
        print(line.strip())    # strip() removes \n

Writing Files

# Write (overwrites existing content)
with open("file.txt", "w") as f:
    f.write("text\n")         # Write string (add \n yourself)
    f.writelines(list_of_str) # Write list of strings

# Append (adds to end)
with open("file.txt", "a") as f:
    f.write("added to end\n")

CSV Files

import csv

# Read with csv.reader (rows as lists)
with open("data.csv") as f:
    reader = csv.reader(f)
    header = next(reader)  # Skip header row
    for row in reader:
        print(row[0])       # Access by index

# Read with DictReader (rows as dicts)
with open("data.csv") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"])   # Access by column name

# Write CSV
with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["col1", "col2"])  # Header
    writer.writerows(data)              # All rows

# Write with DictWriter
with open("out.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "score"])
    writer.writeheader()
    writer.writerows(list_of_dicts)

Key Reminders