Home>Article>Backend Development> 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.
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:
readlines()function to get a list of lines for a given text file.
file.readlines(hint)
# 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)
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
withstatement will replace the following try-catch blockThe Chinese translation of
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()
Hello tutorialsPoint python
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 thewithstatement.
Now let’s recreate the previous example using thewithstatement −
# 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 acontext manager, a class must implement the following two methods −
After implementing these methods, you can use the with statement on objects of the class.
Create a context manager for file writing
The function of this class is the same as the open() methodclass 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
contextlibmodule.The Chinese translation of
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
Hello tutorialsPoint python
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!