What is the use of the WITH statement in Python?


In this article, we will learn about the “with” statement in python and its uses.

  • The with statement in Python replaces a try-catch block with a simple shorthand.

  • More significantly, it ensures that resources are closed immediately after processing.

  • Reading or writing to a file is a common use of the with statement.

  • A context manager is a function or class that supports the with statement. A context manager enables you to open and close resources right when you want to.

  • The open() function, for example, is a context manager. When you use the with statement to call the open() function, the file closes automatically after you've processed it.

Using “with” statement to open and read a file

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the open() function(opens a file and returns a file object as a result) to open the text file in read-only mode by passing the file name, and mode as arguments to it (Here “r” represents read-only mode).

with open(inputFile, 'r') as fileData:
  • Using the readlines() function to obtain the list of lines of a given text file.

file.readlines(hint)
  • Traverse through each line of the given text file using the for loop.

  • Print the corresponding line of a text file.

Example

# input file path inputFile = "ExampleTextFile.txt" print("The lines of a given Text File are:") # Opening the given file in read-only mode. with open(inputFile, 'r') as fileData: # Read the above file lines using readlines() fileLines = fileData.readlines() # Traverse in the each line of the text file for textLine in fileLines: # printing each line print(textLine)

Output

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

With keyword is used not only to open a file in reading mode, but also to assign an alias name to the opened file.

Replacing try-catch blocks using “with” statement

In Python, you may use a try-catch error handling to open and write to a file.

The with statement, under the hood, replaces the below kind of try-catch blocks

Example

# opening the file in write mode using the open() function inputFile = open("tutorialsFile.txt", "w") # handling the exceptions using try-catch blocks try: # writing text into the file inputFile.write("Hello tutorialsPoint python") finally: # closing the file inputFile.close()

Output

Hello tutorialsPoint python

This program opens the file tutorialsFile.txt. If no such file exists, the program creates it. The code then writes "Hello tutorialsPoint python" to the file and then closes it.

There's nothing wrong with this method. However, there is a more elegant method to accomplish this using the with statement.

Now let's use the with statement to recreate the preceding example −

# opening a file in write mode with an alias name using with statement with open("tutorialsFile.txt", "w") as file: # writing text into the file file.write("Hello tutorialsPoint python")

This simplifies the code because the with statement can handle closing the file after it has been utilized. This is why, in general, using the with statement is a preferred technique to open files in Python.

Python “with” statement and context managers

When dealing with files, you could think the with statement only works with the open() function. However, this is not the case. Classes and objects that support the with statement can also be created.

A context manager is a class or function that supports the with statement

If you want to increase resource management in your project, you can use your context manager. To be considered a context manager, a class must implement the following two methods −

  • __enter__()
  • __exit__()

After you've implemented these methods, you can use the with statement on the class's objects.

  • When with statement is called, the __enter__() method is invoked.

  • When you exit the scope of the with block, the __exit__() is invoked.

Creating a file writer context manager

This class functions in the same way as the open() method

class FileWriter(object): def __init__(self, fileName): self.fileName = fileName def __enter__(self): self.file = open(self.fileName, "w") return self.file def __exit__(self, exception_type, exception_value, traceback): self.file.close()

Usage of above program

  • With FileWriter(filename), a new FileWriter object is created and __enter__ () is called.

  • The __enter__() method is used to initialize the resource you want. It opens a text file in this scenario. It also has to return the resource's descriptor, therefore it returns the opened file.

  • The as file assigns the file to a variable file.

  • Finally, the code that will be executed with the acquired resource is placed in the with block after the colon.

  • The __exit__() method is automatically invoked when this code completes execution. It closes the file in this situation.

How to Write Your Context Manager Methods?

The previously written context manager is a class, but what if you want to create a context manager method comparable to the open()function instead? Python also allows you to write context manager methods.

Use the contextlib module to convert a method into a context manager.

Example

# importig the contextmanager from contextlib module from contextlib import contextmanager # Marking the file_open() function as a context manager # using contextmanager decorator @contextmanager def file_open(name): try: file = open(name, "w") yield file finally: file.close() with file_open("exampleFile.txt") as file: file.write("Hello tutorialsPoint python")

exampleFile.txt

Hello tutorialsPoint python

Here, we created a new function and named it with the with keyword. When we call that function, it attempts to open the specified file in writing mode and returns the result. If an error occurs, the file will be closed.

Conclusion

We learned how to use the with statement and examples in this article.

Updated on: 22-Sep-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements