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

</>
Copy
# 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:

  1. The open() function opens example.txt in read mode ("r").
  2. The with statement ensures the file is automatically closed after reading.
  3. We iterate through the file using a for loop, reading one line at a time.
  4. 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

</>
Copy
# Using a context manager to read an entire file at once
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

Explanation:

  1. open("example.txt", "r") opens the file in read mode.
  2. The with statement ensures the file is automatically closed.
  3. read() reads the entire file content into the variable content.
  4. 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

</>
Copy
# 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:

  1. open("example.txt", "r") opens the file in read mode.
  2. The with statement ensures the file is closed after reading.
  3. readlines() reads all lines at once and stores them as a list in lines.
  4. We iterate through lines using a for loop and remove extra spaces using strip().

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

</>
Copy
# 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:

  1. The try block attempts to open and read example.txt.
  2. If the file exists, its content is stored in content and printed.
  3. 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:

  1. Ensures the file is closed automatically after use.
  2. Prevents memory leaks and improves code readability.
  3. Supports multiple reading techniques: line-by-line, full content, and list of lines.
  4. Can be combined with error handling to manage missing files safely.