How to open a file using the with statement
The with keyword in Python is used as a context manager. As in any programming language, the usage of resources like file operations or database connections is very common. But these resources are limited in supply. Therefore, the main problem lies in making sure to release these resources after usage. If they are not released then it will lead to resource leakage and may cause the system to either slow down or crash.
As we know the open() function is generally used for file handling in python. But it is a standard practice to use context managers like with keywords to handle files as it will automatically release files once its usage is complete.
Syntax: with open(file_name) as file
Where: file_name: It is the name of the file.
Example 1: Simple example using with the statement.
We already have a file name geeksforgeeks.txt in our system and it has the following data:
Now we will open the file and read it’ data using the with the statement.
['Geeksforgeeks is best for DSA']
Example 2: We can also use the with a statement to append or write data to the file. We will append the string “Hello geeks!” to our geeksforgeeks.txt file.
['Geeksforgeeks is best for DSAHello Geeks!']
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course