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

<div class="code-mirror  language-python" contenteditable="plaintext-only" spellcheck="false" style="outline: none; overflow-wrap: break-word; overflow-y: auto; white-space: pre-wrap;"><span class="token comment"># input file path</span>
inputFile <span class="token operator">=</span> <span class="token string">"ExampleTextFile.txt"</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"The lines of a given Text File are:"</span><span class="token punctuation">)</span>

<span class="token comment"># Opening the given file in read-only mode.</span>
<span class="token keyword">with</span> <span class="token builtin">open</span><span class="token punctuation">(</span>inputFile<span class="token punctuation">,</span> <span class="token string">'r'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> fileData<span class="token punctuation">:</span>
   
   <span class="token comment"># Read the above file lines using readlines()</span>
   fileLines <span class="token operator">=</span> fileData<span class="token punctuation">.</span>readlines<span class="token punctuation">(</span><span class="token punctuation">)</span>
   
   <span class="token comment"># Traverse in the each line of the text file</span>
   <span class="token keyword">for</span> textLine <span class="token keyword">in</span> fileLines<span class="token punctuation">:</span>
      
      <span class="token comment"># printing each line</span>
      <span class="token keyword">print</span><span class="token punctuation">(</span>textLine<span class="token punctuation">)</span>
</div>

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

<div class="code-mirror  language-python" contenteditable="plaintext-only" spellcheck="false" style="outline: none; overflow-wrap: break-word; overflow-y: auto; white-space: pre-wrap;"><span class="token comment"># opening the file in write mode using the open() function</span>
inputFile <span class="token operator">=</span> <span class="token builtin">open</span><span class="token punctuation">(</span><span class="token string">"tutorialsFile.txt"</span><span class="token punctuation">,</span> <span class="token string">"w"</span><span class="token punctuation">)</span>

<span class="token comment"># handling the exceptions using try-catch blocks</span>
<span class="token keyword">try</span><span class="token punctuation">:</span>
   <span class="token comment"># writing text into the file</span>
   inputFile<span class="token punctuation">.</span>write<span class="token punctuation">(</span><span class="token string">"Hello tutorialsPoint python"</span><span class="token punctuation">)</span>
<span class="token keyword">finally</span><span class="token punctuation">:</span>
   <span class="token comment"># closing the file</span>
   inputFile<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>
</div>

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 ?

<div class="code-mirror  language-python" contenteditable="plaintext-only" spellcheck="false" style="outline: none; overflow-wrap: break-word; overflow-y: auto; white-space: pre-wrap;"><span class="token comment"># opening a file in write mode with an alias name using with statement</span>
<span class="token keyword">with</span> <span class="token builtin">open</span><span class="token punctuation">(</span><span class="token string">"tutorialsFile.txt"</span><span class="token punctuation">,</span> <span class="token string">"w"</span><span class="token punctuation">)</span> <span class="token keyword">as</span> <span class="token builtin">file</span><span class="token punctuation">:</span>
   
   <span class="token comment"># writing text into the file</span>
   <span class="token builtin">file</span><span class="token punctuation">.</span>write<span class="token punctuation">(</span><span class="token string">"Hello tutorialsPoint python"</span><span class="token punctuation">)</span>
</div>

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

<div class="code-mirror  language-python" contenteditable="plaintext-only" spellcheck="false" style="outline: none; overflow-wrap: break-word; overflow-y: auto; white-space: pre-wrap;"><span class="token keyword">class</span> <span class="token class-name">FileWriter</span><span class="token punctuation">(</span><span class="token builtin">object</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
   <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> fileName<span class="token punctuation">)</span><span class="token punctuation">:</span>
      self<span class="token punctuation">.</span>fileName <span class="token operator">=</span> fileName

   <span class="token keyword">def</span> <span class="token function">__enter__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
      self<span class="token punctuation">.</span><span class="token builtin">file</span> <span class="token operator">=</span> <span class="token builtin">open</span><span class="token punctuation">(</span>self<span class="token punctuation">.</span>fileName<span class="token punctuation">,</span> <span class="token string">"w"</span><span class="token punctuation">)</span>
      <span class="token keyword">return</span> self<span class="token punctuation">.</span><span class="token builtin">file</span>

   <span class="token keyword">def</span> <span class="token function">__exit__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> exception_type<span class="token punctuation">,</span> exception_value<span class="token punctuation">,</span> traceback<span class="token punctuation">)</span><span class="token punctuation">:</span>
      self<span class="token punctuation">.</span><span class="token builtin">file</span><span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>
</div>

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

<div class="code-mirror  language-python" contenteditable="plaintext-only" spellcheck="false" style="outline: none; overflow-wrap: break-word; overflow-y: auto; white-space: pre-wrap;"><span class="token comment"># importig the contextmanager from contextlib module</span>
<span class="token keyword">from</span> contextlib <span class="token keyword">import</span> contextmanager

<span class="token comment"># Marking the file_open() function as a context manager</span>
<span class="token comment"># using contextmanager decorator</span>
<span class="token decorator annotation punctuation">@contextmanager</span>
<span class="token keyword">def</span> <span class="token function">file_open</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">:</span>
   <span class="token keyword">try</span><span class="token punctuation">:</span>
      <span class="token builtin">file</span> <span class="token operator">=</span> <span class="token builtin">open</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> <span class="token string">"w"</span><span class="token punctuation">)</span>
      <span class="token keyword">yield</span> <span class="token builtin">file</span>
   <span class="token keyword">finally</span><span class="token punctuation">:</span>
      <span class="token builtin">file</span><span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token keyword">with</span> file_open<span class="token punctuation">(</span><span class="token string">"exampleFile.txt"</span><span class="token punctuation">)</span> <span class="token keyword">as</span> <span class="token builtin">file</span><span class="token punctuation">:</span>
   <span class="token builtin">file</span><span class="token punctuation">.</span>write<span class="token punctuation">(</span><span class="token string">"Hello tutorialsPoint python"</span><span class="token punctuation">)</span>
</div>

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: 2022-09-22T12:50:09+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements