with Statement

Introduction

The with statement in Python is used to simplify resource management. It automatically handles the setup and cleanup of resources such as files, database connections, network connections, and other objects that need to be properly closed after use.

The with statement works with Context Managers, which ensure that resources are released correctly even if an error occurs during execution.

Using the with statement makes code:

  • Cleaner

  • Safer

  • More readable

  • Less error-prone

  • Easier to maintain


Why Use the with Statement?

Consider reading a file without using with.

Without with Statement

file = open("sample.txt", "r")

content = file.read()

print(content)

file.close()

The programmer must remember to close the file manually.


Problem

If an exception occurs before file.close(), the file remains open.

file = open("sample.txt", "r")

raise Exception("Error Occurred")

file.close()

The file never gets closed.


Using the with Statement

Example

with open("sample.txt", "r") as file:

    content = file.read()

    print(content)

Python automatically closes the file when the block finishes.


Syntax of with Statement

with expression as variable:

    # code block

Example

with open("data.txt", "r") as file:

    print(file.read())

How the with Statement Works

The with statement performs two actions:

  1. Acquires the resource.

  2. Releases the resource automatically.

Flow

Open Resource
      │
      ▼
Execute Code
      │
      ▼
Close Resource

This happens even if an exception occurs.


Reading a File

Example

with open("sample.txt", "r") as file:

    data = file.read()

    print(data)

Writing to a File

Example

with open("output.txt", "w") as file:

    file.write(
        "Hello Python"
    )

The file is automatically saved and closed.


Appending to a File

Example

with open("log.txt", "a") as file:

    file.write(
        "New Log Entry\n"
    )

Reading File Line by Line

Example

with open("sample.txt", "r") as file:

    for line in file:

        print(line)

Multiple Files Using with

Example

with open("source.txt", "r") as source, \
     open("destination.txt", "w") as destination:

    destination.write(
        source.read()
    )

Exception Handling with with Statement

Example

try:

    with open(
        "sample.txt",
        "r"
    ) as file:

        print(
            file.read()
        )

except FileNotFoundError:

    print(
        "File Not Found"
    )

Even if an exception occurs, Python closes the file automatically.


Checking Automatic File Closure

Example

with open("sample.txt", "r") as file:

    print(
        file.closed
    )

Output

False

Inside the block, the file is open.


After Block

with open("sample.txt", "r") as file:

    pass

print(
    file.closed
)

Output

True

The file is automatically closed.


Working with CSV Files

Example

import csv

with open(
    "users.csv",
    "r"
) as file:

    reader = csv.reader(
        file
    )

    for row in reader:

        print(row)

Working with JSON Files

Example

import json

with open(
    "data.json",
    "r"
) as file:

    data = json.load(
        file
    )

    print(data)

Selenium Automation Example: Reading Test Data

Automation frameworks often store test data in files.

Example

with open(
    "credentials.txt",
    "r"
) as file:

    username = file.readline()

    password = file.readline()

Selenium Automation Example: Writing Test Logs

Example

with open(
    "execution_log.txt",
    "a"
) as file:

    file.write(
        "Login Test Passed\n"
    )

Selenium Automation Example: Reading Locators

locators.json

{
    "login_button": "login",
    "username": "user"
}

Python Code

import json

with open(
    "locators.json",
    "r"
) as file:

    locators = json.load(
        file
    )

print(
    locators["login_button"]
)

Database Example Using with

Some database libraries support context managers.

Example

import sqlite3

with sqlite3.connect(
    "users.db"
) as connection:

    cursor = connection.cursor()

    cursor.execute(
        "SELECT * FROM users"
    )

    print(
        cursor.fetchall()
    )

The database connection is automatically managed.


Nested with Statements

Example

with open(
    "source.txt",
    "r"
) as source:

    with open(
        "destination.txt",
        "w"
    ) as destination:

        destination.write(
            source.read()
        )

Preferred Approach

with open(
    "source.txt",
    "r"
) as source, \
     open(
         "destination.txt",
         "w"
     ) as destination:

    destination.write(
        source.read()
    )

Cleaner and more readable.


Common Mistakes Beginners Make

Forgetting to Close Files

Incorrect

file = open(
    "sample.txt",
    "r"
)

print(
    file.read()
)

File remains open.


Correct

with open(
    "sample.txt",
    "r"
) as file:

    print(
        file.read()
    )

Using try-finally Instead of with

Older Approach

file = open(
    "sample.txt",
    "r"
)

try:

    print(
        file.read()
    )

finally:

    file.close()

Better Approach

with open(
    "sample.txt",
    "r"
) as file:

    print(
        file.read()
    )

Accessing File After Block Ends

Incorrect

with open(
    "sample.txt",
    "r"
) as file:

    pass

file.read()

Output

ValueError:
I/O operation on closed file

Advantages of with Statement

  • Automatic resource cleanup

  • Prevents resource leaks

  • Improves readability

  • Simplifies exception handling

  • Reduces code complexity

  • Safer file handling

  • Recommended Python practice


Real-World Selenium Framework Uses

The with statement is commonly used for:

  • Reading configuration files

  • Reading test data files

  • Writing execution logs

  • Handling CSV files

  • Handling JSON files

  • Managing database connections

  • Reading locator files

  • Report generation


Best Practices

Always Use with for File Operations

with open(
    "data.txt",
    "r"
) as file:

Use Meaningful Variable Names

Good

with open(
    "users.csv",
    "r"
) as csv_file:

Avoid

with open(
    "users.csv",
    "r"
) as f:

for large projects.


Handle Exceptions When Necessary

try:

    with open(
        "data.txt",
        "r"
    ) as file:

        print(
            file.read()
        )

except FileNotFoundError:

    print(
        "File Not Found"
    )

Use Multiple Context Managers When Appropriate

with open(
    "input.txt",
    "r"
) as source, \
     open(
         "output.txt",
         "w"
     ) as destination:

Conclusion

The with statement is a powerful Python feature that simplifies resource management by automatically handling setup and cleanup operations. It is most commonly used for file handling but is also useful for database connections, network resources, and other managed objects.

In Selenium automation frameworks, the with statement is frequently used for reading configuration files, test data files, JSON files, CSV files, and logging information. Using with ensures cleaner code, better resource management, and fewer runtime issues.


Frequently Asked Questions (FAQs)

What is the purpose of the with statement?

It automatically manages resources and ensures proper cleanup.


Does with automatically close files?

Yes. Files are automatically closed when the block exits.


Can with handle exceptions?

Yes. Resources are still cleaned up even if exceptions occur.


Can multiple files be opened using with?

Yes.

with open("a.txt") as file1, \
     open("b.txt") as file2:

Is with recommended for file handling?

Yes. It is the preferred and most Pythonic approach.


Key Takeaways

  • The with statement simplifies resource management.

  • Files are automatically closed after use.

  • It prevents resource leaks.

  • It improves readability and maintainability.

  • It works with Context Managers.

  • It is commonly used for files, databases, and logs.

  • It handles cleanup even when exceptions occur.

  • Multiple resources can be managed in a single with statement.

  • It is widely used in Selenium automation frameworks.

  • Always prefer with over manually opening and closing resources.