Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to open a file using the with statement
Next article icon

How to open a file using the with statement

Last Updated : 13 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Python with open() Syntax:

Syntax: 

with open(file_path, mode, encoding) as file:

        ...

file_path: It is the path to the file to open

mode: mode of operation on the file. ex.: read, write etc. (represented by r, w, r+, w+, rb, wb etc.)

encoding: read the file in correct encoding format.

Example 1: Simple Example Using The with Statement

We already have a file name geeksforgeeks.txt in our system, and it has the following data:

geeksforgeeks,txt

Now we will open the file and read the contents of the file using with open() statement:

Python3
 with open("geeksforgeeks.txt","r") as gfg_file:     file_content = gfg_file.read()     print(file_content)      

Output:

GeeksForGeeks is best for DSA

Note: Here we have used mode as "r" to read the data, because the target file has text data. In case we are reading some binary file, we need to use "rb" as the mode.

Example 2: We can also use the with 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("\nHello Geeks!")      # reading the file contents # to verify if successfully appended the data with open("geeksforgeeks.txt","r") as gfg_file:     content = gfg_file.read()     print(content) 

Output:

GeeksForGeeks is best for DSA Hello Geeks!

Note: Here we have used "a" as the mode of opening the file, this is because we want to append to the file data. Instead, if we wanted to overwrite the file data, we would use the "w" mode.

Example 3: Using nested with open statement to open multiple files

How to open a file using the with statement
links.txt

We have defined a links.txt file containing some random links. We will open the geeksforgeeks.txt file mentioned above and append the content of the links file into the geeksforgeeks.txt file.

Python3
# appending string to file with open("geeksforgeeks.txt", "a") as gfg_file:     gfg_file.write("\nHello Geeks!")      with open("links.txt", 'r') as links_file:         lines = links_file.readlines()      gfg_file.writelines(lines) 

geeksforgeeks.txt file contents after modification:

How to open a file using the with statement
geeksforgeeks,txt

Here, we can see that the contents of the links.txt file has been added to the geeksforgeeks.txt file after running the script.

Difference of using open() vs with open()

Although the function of using open() and with open() is exactly same but, there are some important differences:

  • Using open() we can use the file handler as long as the file has not been explicitly closed using file_handler.close(), but in case of using with open() context manager, we cannot use a file handler outside the with block. It will raise ValueError: I/O operation on closed file in that case.
  • While using open() we need to explicitly close an opened file instance, else other parts of code may face errors while opening the same file. In with open() the closing of the file is handled by the context manager.
  • Using with open() context statement makes the code more tidy as we can easily separate between code block by difference in indents. In case of open(), we might miss closing the file instance, this may cause memory leaks and other I/O operation errors.

Next Article
How to open a file using the with statement

D

ddeevviissaavviittaa
Improve
Article Tags :
  • Python
  • Blogathon
  • Blogathon-2021
  • python-file-handling
Practice Tags :
  • python

Similar Reads

    How to open multiple files using "with open" in Python?
    Python has various highly useful methods for working with file-like objects, like the with feature. But what if we need to open several files in this manner? You wouldn't exactly be "clean" if you had a number of nested open statements. In this article, we will demonstrate how to open multiple files
    2 min read
    with statement in Python
    The with statement in Python is used for resource management and exception handling. It simplifies working with resources like files, network connections and database connections by ensuring they are properly acquired and released. When we open a file, we need to close it ourself using close(). But
    6 min read
    How to open External Programs using Tkinter?
    Prerequisite: Tkinter, os Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest
    2 min read
    How to Open a PL/SQL File?
    In database management and application development, PL/SQL (Procedural Language/Structured Query Language) files play an important role. These files contain stored procedures, functions, triggers, and other programmatic constructs essential for Oracle database systems. Opening a PL/SQL file is the f
    4 min read
    How to Open a TextEditor in an Ubuntu Terminal
    Ubuntu and other Linux distributions using the GNOME desktop environment come pre-installed with a default text editor known as the GNOME Text Editor, commonly referred to as Gedit. Gedit is a user-friendly, lightweight, and powerful text editor with rich features, making it an ideal choice for casu
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences