Python with Keyword/Statement

The with keyword or statement in Python is used to acquire some resource, and the resource gets released while leaving the with context. For example:

with open("codescracker.txt") as fob:
    content = fob.read()
    print(content)

The snapshot given below shows the sample output produced by above Python program, demonstrating the with keyword or statement:

python with keyword

You're seeing this output, because in the current directory (the directory where the above Python program or source code is saved), there is a file named codescracker.txt with the same content as displayed in the sample output. Here is the snapshot of the current directory, with opened same file, used in the sample run:

python with statement

If opening mode is not provided while opening the file using open(), then by default, the file gets opened in r mode, which is for reading the file.

After leaving the with context, the file automatically gets closed. Therefore, if you try to execute fob.read() again, after the with context, then you'll see an error on output, because as soon as we exit from the with context, the file automatically gets closed. For example, the following program:

with open("codescracker.txt") as fob:
    content = fob.read()
    print(content)

print(fob.read())

produces:

python with keyword example

But the same program can be created, without using with statement or keyword, in this way:

fob = open("codescracker.txt")
print(fob.read())

fob.seek(0)

print(fob.read())

Note - The seek() function is used to move the file pointer at beginning of the file.

The output produced by above program, is:

python with statement example

This is because, in previous program, the with statement acquire the resource of opening the file and reading its content. Therefore, after existing from the with context, the resource gets released, therefore accessing the file using its objects named fob, produces an error saying that the file is closed. But in this program, the file is opened, until we use close() function to close the file.

A context manager is basically an object that defines the runtime context to be established when executing a with statement.

For example, the open statement is itself a context manager. It opens a file, keep the file open as long as execution is in the context of, with statement, of course, where you use it. And close it, when you leave the context, without concerning the matter, whether you've left it because of exception, or simply during the regular flow of control.

Here is another example program in Python, demonstrating the with statement:

with open("codescracker.txt") as ifob, open("myfile.txt", "w") as ofob:
    for line in ifob:
        ofob.write(line)
    print("The content of 'codescracker.txt' is copied to 'myfile.txt'")

The output is:

The content of 'codescracker.txt' is copied to 'myfile.txt'

After executing this program, a file named myfile.txt gets created in the current directory, and the content of codescracker.txt file gets copied into it. And if this file already exists, then its previous content gets replaced with the new content.

Python provides contextlib module that helps in constructing your own context manager, using the @contextmanager decorator. For example, the following program changes the current working directory temporarily, to work with that directory, and when the work is completed, then back to the actual current directory, for the program.

from contextlib import contextmanager
import os

@contextmanager
def working_dir(workPath):
    cur_dir = os.getcwd()
    os.chdir(workPath)
    try:
        yield
    finally:
        os.chdir(cur_dir)

with working_dir("C:/Users/DEV/codescracker.com/practice"):
    print("The current working directory is:", os.getcwd())
    # your code to work with this directory

print("\nNow The current directory is:", os.getcwd())

The output is:

The current working directory is: C:\Users\DEV\codescracker.com\practice

Now The current directory is: C:\Users\DEV\codescracker.com

where C:\Users\DEV\codescracker.com is the actual current directory for the above program, because our Python program's source code is saved in this directory.

Since the directory is changed for temporary, therefore you can use your code to work with that directory. And as soon as we exit from the with construct, we get back to the original current directory. Let's create a complete practical example to demonstrate the concept:

from contextlib import contextmanager
import os

@contextmanager
def working_dir(workPath):
    cur_dir = os.getcwd()
    os.chdir(workPath)
    try:
        yield
    finally:
        os.chdir(cur_dir)

with working_dir("C:/Users/DEV/codescracker.com/practice"):
    print("The current working directory is:", os.getcwd())
    print("\nEnter the Name of File to Create: ", end="")
    fileName = input()
    fo = open(fileName, "w")
    print("\nThe file is created successfully.")
    print("Now Enter the content: ", end="")
    content = input()
    fo.write(content)
    print("\nThe content is written inside the file.")

print("\nNow The current directory is:", os.getcwd())

Here is its sample run with user input myfile.txt as name of file, Python is Fun! as content:

python with keyword program

I don't know how the with keyword helps in your application, but the actual working of with is the one that described above.

Note - The yield keyword similar to return except that, yield returns a generator.

After executing the above program, with same inputs as provided in above sample run. A file named myfile.txt with Python is Fun! as content will get created in that directory, used as parameter of working_dir() function, after the with keyword, instead of creating in the current directory, where the Python source code is saved.

Python Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!