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 the open() 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
Use "with" statement instead of try-catch block
Under the hood, the
with statement will replace the following try-catch block The 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 thewith statement.
Now let’s recreate the previous example using thewith statement −
# 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")
Python "with" statement and context manager
A context manager is a class or function that supports the
with statement
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() 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()
Convert a method to a context manager using the
contextlib module. 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")
Hello tutorialsPoint python
in conclusion
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!