Read a File using a Context Manager in Python
To read a file in Python using a context manager, use the with
statement. This ensures that the file is automatically closed after reading, preventing resource leaks. The most common approach is using with open()
, which allows reading the file’s content safely and efficiently.
Examples to Read a File using a Context Manager
1. Reading a File Line by Line
In this example, we will read a text file line by line using a context manager. This method is memory-efficient, as it reads one line at a time instead of loading the entire file into memory.

main.py
# Using a context manager to read a file line by line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Explanation:
- The
open()
function opensexample.txt
in read mode ("r"
). - The
with
statement ensures the file is automatically closed after reading. - We iterate through the file using a
for
loop, reading one line at a time. strip()
removes any leading and trailing whitespace, including newline characters.
Output (if example.txt contains):
Hello World!
Hello User!
Hello Arjun!
2. Reading an Entire File at Once
In this example, we will read the entire content of a file at once using the read()
method. This is useful when working with small files where loading all content into memory is not an issue.

main.py
# Using a context manager to read an entire file at once
with open("example.txt", "r") as file:
content = file.read()
print(content)
Explanation:
open("example.txt", "r")
opens the file in read mode.- The
with
statement ensures the file is automatically closed. read()
reads the entire file content into the variablecontent
.print(content)
displays the file’s content on the console.
Output:
Hello World!
Hello User!
Hello Arjun!
3. Reading a File as a List of Lines
In this example, we will read the entire file into a list of lines using readlines()
. Each line in the file will be stored as an element in a list.
main.py
# Using a context manager to read file lines into a list
with open("example.txt", "r") as file:
lines = file.readlines()
# Printing each line
for line in lines:
print('Line:', line.strip())
Explanation:
open("example.txt", "r")
opens the file in read mode.- The
with
statement ensures the file is closed after reading. readlines()
reads all lines at once and stores them as a list inlines
.- We iterate through
lines
using afor
loop and remove extra spaces usingstrip()
.
Output:
Line: Hello World!
Line: Hello User!
Line: Hello Arjun!
4. Reading a File with Exception Handling
In this example, we will safely handle errors while reading a file using a try-except
block. This ensures that the program does not crash if the file is missing.
main.py
# Using a context manager with error handling
try:
with open("example.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("Error: The file does not exist.")
Explanation:
- The
try
block attempts to open and readexample.txt
. - If the file exists, its content is stored in
content
and printed. - If the file is missing, a
FileNotFoundError
is caught, and an error message is printed.
Output (if file exists):
Hello World!
Hello User!
Hello Arjun!
Output (if file does not exist):
Error: The file does not exist.
Conclusion
In this tutorial, we covered examples using a context manager (with open()
) to read a file in Python. This approach:
- Ensures the file is closed automatically after use.
- Prevents memory leaks and improves code readability.
- Supports multiple reading techniques: line-by-line, full content, and list of lines.
- Can be combined with error handling to manage missing files safely.