Skip to content
Related Articles

Related Articles

Improve Article

How to open a file using the with statement

  • Last Updated : 13 Sep, 2021

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.

Python3




with open("geeksforgeeks.txt","r") as gfg_file:
   lines = gfg_file.readlines()
   print(lines)


Output:

['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.

Python3




# appending string to file
with open("geeksforgeeks.txt","a") as gfg_file:
   gfg_file.write("Hello Geeks!")
      
# reading the file contents
# to veriy if successfully appended the data
with open("geeksforgeeks.txt","r") as gfg_file:
    lines = gfg_file.readlines()
    print(lines)


Output:

['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




My Personal Notes arrow_drop_up
Recommended Articles
Page :