01 / 20

Reading Files with
Context Managers

Master Python's open() function and the with statement to read files safely, cleanly, and without resource leaks.

Python

What Is a File in Python?

A file is a named location on disk that stores data: text documents, CSV data, configuration settings, log output, and more. Python treats files as objects with methods for reading, writing, and closing.

File Object
Created by calling open(): it represents a connection between your program and data on disk.
File Handle
The variable that holds the file object. You use it to call methods like .read() and .close().

The open() Function

Python's built-in open() function takes a filename (and optionally a mode) and returns a file object.

Python
f = open("data.txt", "r")
content = f.read()
print(content)
f.close()
"r" mode
Read mode (default): opens the file for reading text. Raises an error if the file does not exist.
.read()
Returns the entire file contents as a single string.
.close()
Releases the file handle back to the OS. You must call this manually.

The Problem with Manual Closing

If an error occurs between open() and close(), the close() line never runs. The file stays open, leaking a system resource.

Python
f = open("data.txt", "r")
content = f.read()
result = 1 / 0    # ZeroDivisionError!
f.close()         # Never reached!
open() .read() ERROR .close() File handle leaks: close() is never called

Enter the Context Manager

A context manager is a Python pattern that automatically sets up and tears down a resource. The with statement activates it.

Python
with open("data.txt", "r") as f:
    content = f.read()
    print(content)
# f.close() is called automatically here

The with Statement: Core Rule

with open( "file.txt" , "r" ) as f : keyword function call mode alias variable # indented block: file is open here content = f.read() ✓ File automatically closes when block ends

Three Ways to Read

.read()
Returns the entire file as one string. Best for small files.
.readline()
Returns one line at a time (including the newline character).
.readlines()
Returns a list of all lines, each as a separate string.
Python
with open("data.txt") as f:
    all_text  = f.read()       # "line1\nline2\nline3\n"

with open("data.txt") as f:
    first    = f.readline()   # "line1\n"

with open("data.txt") as f:
    lines    = f.readlines()  # ["line1\n", "line2\n", ...]

Manual vs Context Manager

Manual open/close f = open("f.txt") data = f.read() # if error here... f.close() ✕ close() may be skipped ✕ Resource leak risk ✕ More code to write with statement with open("f.txt") as f: data = f.read() # error? still closes! ✓ Always closes the file ✓ Exception-safe ✓ Cleaner, shorter code ✓ Pythonic best practice

Iterating Over Lines

A file object is iterable: you can loop over it directly with a for loop. This is the most memory-efficient way to process a file line by line.

Python
with open("scores.txt") as f:
    for line in f:
        line = line.strip()  # remove \n
        print(line)

Step-by-Step Checklist

1
Identify the file path. Use a relative path like "data.txt" or an absolute path like "/home/user/data.txt".
2
Choose a read mode. Use "r" for text (default), or "rb" for binary data (images, PDFs).
3
Write the with statement. with open(path, mode) as f: ensures auto-close.
4
Read the data inside the block. Use .read(), .readline(), .readlines(), or a for loop.
5
Process after the block. The file is closed, but your variables (like content) still hold the data.

Example 1: Read Entire File

Read a greeting message from a file and display it.

Python
# greeting.txt contains:
# Hello, World!
# Welcome to Python.

with open("greeting.txt", "r") as f:
    message = f.read()

print(message)
# Output:
# Hello, World!
# Welcome to Python.

Example 2: Count Lines in a File

Count how many lines are in a text file using a for loop.

Python
count = 0

with open("poem.txt") as f:
    for line in f:
        count += 1

print(f"Total lines: {count}")

Example 3: Parse Structured Data

Read a file where each line contains a name and score separated by a comma, and compute the average.

Python
# scores.txt:
# Alice,92
# Bob,85
# Carol,97

total = 0
count = 0

with open("scores.txt") as f:
    for line in f:
        name, score = line.strip().split(",")
        total += int(score)
        count += 1

avg = total / count
print(f"Average: {avg}")  # Average: 91.333...

Common Mistakes

✕ Forgetting to Close
Using open() without with and forgetting .close(): causes resource leaks that crash long-running programs.
✕ Reading After Close
Trying to call f.read() outside the with block: the file is already closed, raising a ValueError.
✕ Ignoring Newlines
Comparing lines without calling .strip(): "hello\n" != "hello" causes silent logic errors.

Comparison Summary

.read() .readline() .readlines() for loop
Returns One string One line List of strings One line/iteration
Memory Loads all Minimal Loads all Minimal
Best For Small files Header lines Index access Large files
Includes \n Yes Yes Yes Yes

Question 1 of 5

What is the main advantage of using a with statement when opening a file?

Question 2 of 5

What does f.readlines() return?

Question 3 of 5

What happens when the print(f.read()) line executes?

Question 4 of 5

You have a 10 GB log file. Which reading approach is most memory-efficient?

Question 5 of 5

The program never prints "Found Bob!" Why?