Home>Article>Backend Development> What is the use of WITH statement in Python?

What is the use of WITH statement in Python?

王林
王林 forward
2023-08-18 22:53:14 1797browse

What is the use of WITH statement in Python?

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

  • In Python, the with statement replaces the try-catch block in a concise way.

  • More importantly, it ensures that the resource is closed immediately after processing.

  • Using the with statement to read or write files is a common usage.

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

  • For example, the open() function is a context manager. When you call the open() function using the with statement, the file is automatically closed after processing the file.

Use the "with" statement to open and read files

Algorithm (steps)

The following are the algorithms/steps to perform the required task:

  • Use theopen()function (which opens a file and returns a file object as a result) to open a text file in read-only mode (the "# here" by passing it the filename and mode as arguments) ##r" indicates read-only mode).

  • with open(inputFile, 'r') as fileData:
  • Use the

    readlines()function to get a list of lines for a given text file.

  • file.readlines(hint)
  • Use a for loop to iterate through each line of a given text file.

  • Print the corresponding lines of the text file.

  • The Chinese translation of
Example

is:

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

Use the keyword `with` not only to open a file in read mode, but also to assign an alias to the opened file.

Use "with" statement instead of try-catch block

In Python, you can use try-catch error handling to open and write files.

Under the hood, the

withstatement will replace the following try-catch blockThe Chinese translation of

Example

is:

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 the file.

There is no problem with this method. However, this task can be accomplished more elegantly using the

withstatement.

Now let’s recreate the previous example using the

withstatement −

# 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 used. This is why generally using the with statement is the preferred technique for opening files in Python.

Python "with" statement and context manager

When processing files, you may think that the with statement only applies to the open() function. However, it is not. Classes and objects that support the with statement can also be created.

A context manager is a class or function that supports the

withstatement

If you want to add resource management to your project, you can use a context manager. To be considered a

context manager, a class must implement the following two methods −

    __enter__()
  • __exit__()
  • After implementing these methods, you can use the with statement on objects of the class.

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

  • When you exit the scope of the with block, the __exit__() method will be called.

Create a context manager for file writing

The function of this class is the same 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()

How to use the above program

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

  • __enter__() method is used to initialize the required resources. In this case it opens a text file. It must also return the descriptor of the resource and therefore the open file.

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

  • Finally, in the with block after the colon, place the code that will be executed with the obtained resource.

  • When this code execution is completed, the __exit__() method will be automatically called. In this case it closes the file.

How to write your context manager methods?

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

Convert a method to a context manager using the

contextlibmodule.The Chinese translation of

Example

is:

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")
The translation of

exampleFile.txt

is:

exampleFile.txt

Hello tutorialsPoint python

Here, we use the with keyword to create a new function and name it. When we call this function, it tries to open the specified file in write mode and returns the result. If an error occurs, the file will be closed.

in conclusion

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

The above is the detailed content of What is the use of WITH statement in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete