What is the use of the WITH statement in Python?

The with statement in Python provides an elegant way to handle resources like files, database connections, and network sockets. It automatically manages resource cleanup and replaces complex try-catch blocks with cleaner, more readable code.

What is the WITH Statement?

The with statement works with context managers to ensure resources are properly opened and closed. Key benefits include ?

  • Automatic resource cleanup

  • Exception safety

  • Cleaner, more readable code

  • No need for explicit close() calls

Reading Files with WITH Statement

The most common use case is file handling. Here's how to read a file using the with statement ?

# Creating a sample file content
content = """Good Morning this is Tutorials Point sample File
Consisting of Specific
Good source codes in Python,Seaborn,Scala
Summary and Explanation"""

# Write to file first
with open("sample_file.txt", "w") as f:
    f.write(content)

# Read the file using with statement
print("The lines of a given Text File are:")
with open("sample_file.txt", "r") as file_data:
    file_lines = file_data.readlines()
    for text_line in file_lines:
        print(text_line.strip())
The lines of a given Text File are:
Good Morning this is Tutorials Point sample File
Consisting of Specific
Good source codes in Python,Seaborn,Scala
Summary and Explanation

Replacing Try-Finally Blocks

The with statement replaces verbose try-finally blocks. Compare these approaches ?

Traditional Try-Finally Approach

# Traditional method with explicit resource management
file_handle = None
try:
    file_handle = open("tutorial_file.txt", "w")
    file_handle.write("Hello TutorialsPoint Python")
finally:
    if file_handle:
        file_handle.close()

WITH Statement Approach

# Elegant approach using with statement
with open("tutorial_file.txt", "w") as file_handle:
    file_handle.write("Hello TutorialsPoint Python")

# File is automatically closed after the block
# Read back to verify
with open("tutorial_file.txt", "r") as f:
    print(f.read())
Hello TutorialsPoint Python

Creating Custom Context Managers

You can create custom context managers by implementing __enter__() and __exit__() methods ?

class FileWriter:
    def __init__(self, filename):
        self.filename = filename
    
    def __enter__(self):
        print(f"Opening file: {self.filename}")
        self.file = open(self.filename, "w")
        return self.file
    
    def __exit__(self, exception_type, exception_value, traceback):
        print(f"Closing file: {self.filename}")
        if self.file:
            self.file.close()

# Using the custom context manager
with FileWriter("custom_file.txt") as writer:
    writer.write("Custom context manager example")

# Read back the file
with open("custom_file.txt", "r") as f:
    print("File content:", f.read())
Opening file: custom_file.txt
Closing file: custom_file.txt
File content: Custom context manager example

Using contextlib for Function-Based Context Managers

The contextlib module provides a decorator to create context managers from functions ?

from contextlib import contextmanager

@contextmanager
def file_manager(filename, mode):
    print(f"Opening {filename} in {mode} mode")
    try:
        file_handle = open(filename, mode)
        yield file_handle
    finally:
        print(f"Closing {filename}")
        file_handle.close()

# Using the function-based context manager
with file_manager("function_file.txt", "w") as f:
    f.write("Function-based context manager")

with file_manager("function_file.txt", "r") as f:
    print("Content:", f.read())
Opening function_file.txt in w mode
Closing function_file.txt
Opening function_file.txt in r mode
Content: Function-based context manager
Closing function_file.txt

Comparison of Context Manager Approaches

Approach Best For Complexity
Class-based Complex resource management Higher
Function-based (@contextmanager) Simple resource management Lower
Built-in (open(), etc.) Common operations Lowest

Conclusion

The with statement is essential for proper resource management in Python. It ensures automatic cleanup, improves code readability, and prevents resource leaks. Use it whenever working with files, database connections, or any resources that need explicit cleanup.

Updated on: 2026-03-26T21:56:37+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements