Skip to content
Related Articles

Related Articles

How to open a file using the with statement

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 09 Nov, 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 verify 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!']
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!