Lesson 106 min read

File I/O

Read and write files — because your data deserves to outlive your program

Opening Files — The with Statement

Reading a file in Python is like checking out a library book: you open it, read it, and then close it when you're done. If you forget to close it, bad things can happen (corrupted data, locked files, resource leaks).

The with statement is your best friend here — it automatically closes the file when you're done, even if an error occurs. Always use it.

The open() function takes a filename and a mode:

  • "r" — Read (default). File must exist.
  • "w" — Write. Creates file or overwrites existing content!
  • "a" — Append. Adds to the end without erasing.
  • "x" — Exclusive create. Fails if the file already exists.
  • Add "b" for binary mode: "rb", "wb".

Writing & Reading Files

# Writing a file
with open("grocery_list.txt", "w") as f:
f.write("Apples\n")
f.write("Bread\n")
f.write("Milk\n")
f.write("Cheese\n")
print("File written!")
# Reading the entire file
with open("grocery_list.txt", "r") as f:
content = f.read()
print("Full content:")
print(content)
# Reading line by line (memory efficient for big files)
with open("grocery_list.txt", "r") as f:
for line_number, line in enumerate(f, start=1):
print(f"{line_number}: {line.strip()}")
Output
File written!
Full content:
Apples
Bread
Milk
Cheese

1: Apples
2: Bread
3: Milk
4: Cheese

Reading Methods Compared

Python gives you three ways to read file contents:

  • .read() — Returns the entire file as one big string. Great for small files.
  • .readline() — Returns one line at a time. Call it again for the next line.
  • .readlines() — Returns a list of all lines. Each line includes the \n newline character.
  • Iterating the file object — The best way for large files. Reads one line at a time without loading the whole thing into memory.

Appending & Using readlines()

# Append to an existing file
with open("grocery_list.txt", "a") as f:
f.write("Eggs\n")
f.write("Butter\n")
# Read all lines into a list
with open("grocery_list.txt", "r") as f:
lines = f.readlines()
print("Raw lines:", lines[:3]) # First 3 (notice the \n)
# Clean up — strip whitespace from each line
clean_lines = [line.strip() for line in lines]
print("Clean lines:", clean_lines)
print(f"Total items: {len(clean_lines)}")
Output
Raw lines: ['Apples\n', 'Bread\n', 'Milk\n']
Clean lines: ['Apples', 'Bread', 'Milk', 'Cheese', 'Eggs', 'Butter']
Total items: 6

Working with CSV Files

CSV (Comma-Separated Values) is one of the most common file formats for data. Python has a built-in csv module, but for simple cases you can handle it with just .split() and f-strings.

CSV Basics

import csv
# Writing a CSV file
students = [
["Name", "Grade", "Score"],
["Alice", "A", "95"],
["Bob", "B", "87"],
["Charlie", "A", "92"],
]
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(students)
print("CSV written!")
# Reading a CSV file
with open("students.csv", "r") as f:
reader = csv.reader(f)
header = next(reader) # Skip the header row
print(f"Columns: {header}")
for row in reader:
print(f"{row[0]} scored {row[2]} (Grade {row[1]})")
print()
# Using DictReader for named columns
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['Name']}: {row['Score']}")
Output
CSV written!
Columns: ['Name', 'Grade', 'Score']
Alice scored 95 (Grade A)
Bob scored 87 (Grade B)
Charlie scored 92 (Grade A)

Alice: 95
Bob: 87
Charlie: 92
Note: Always use the with statement when working with files. It's like having a responsible roommate who always turns off the lights when leaving — your files get properly closed even if your code crashes halfway through.

Quick check

What does the "w" mode do if the file already exists?
ComprehensionsError Handling