Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 delete from a pickle file in Python?
Next article icon

How to open and close a file in Python

Last Updated : 25 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

There might arise a situation where one needs to interact with external files with Python. Python provides inbuilt functions for creating, writing, and reading files. In this article, we will be discussing how to open an external file and close the same using Python.

Opening a file in Python

There are two types of files that can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode).

Note: The file should exist in the same directory as the Python script, otherwise, the full address of the file should be written.
 

Syntax: File_object = open(“File_Name”, “Access_Mode”)

Parameters: 

  • File_Name: It is the name of the file that needs to be opened.
  • Access_Mode: Access modes govern the type of operations possible in the opened file. The below table gives the list of all access mode available in python
OperationSyntaxDescription
Read OnlyrOpen text file for reading only.
Read and Writer+Open the file for reading and writing.
Write OnlywOpen the file for writing.
Write and Readw+Open the file for reading and writing. Unlike “r+” is doesn’t raise an I/O error if file doesn’t exist.
Append OnlyaOpen the file for writing and creates new file if it doesn’t exist. All additions are made at the end of the file and no existing data can be modified.
Append and Reada+Open the file for reading and writing and creates new file if it doesn’t exist. All additions are made at the end of the file and no existing data can be modified.

Example 1: Open and read a file using Python

In this example, we will be opening a file to read-only. The initial file looks like the below: 

 


Code:

Python3

# open the file using open() function
file = open("sample.txt")
 
# Reading from file
print(file.read())
                      
                       

Here we have opened the file and printed its content.

Output: 

Hello Geek! This is a sample text file for the example.

Example 2:  Open and write in a file using Python

In this example, we will be appending new content to the existing file. So the initial file looks like the below: 

 

Code: 

Python3

# open the file using open() function
file = open("sample.txt", 'a')
 
# Add content in the file
file.write(" This text has been newly appended on the sample file")
                      
                       

Now if you open the file you will see the below result, 

Output: 

 


Example 3: Open and overwrite a file using Python

In this example, we will be overwriting the contents of the sample file with the below code:

Code:

Python3

# open the file using open() function
file = open("sample.txt", 'w')
 
# Overwrite the file
file.write(" All content has been overwritten !")
                      
                       

The above code leads to the following result, 

Output: 

 

Example 4: Create a file if not exists in Python

The path.touch() method of the pathlib module creates the file at the path specified in the path of the path.touch().

Python3

from pathlib import Path
 
my_file = Path('test1/myfile.txt')
my_file.touch(exist_ok=True)
f = open(my__file)
                      
                       

Output:

 

Closing a file in Python

As you notice, we have not closed any of the files that we operated on in the above examples. Though Python automatically closes a file if the reference object of the file is allocated to another file, it is a standard practice to close an opened file as a closed file reduces the risk of being unwarrantedly modified or read.
Python has a close() method to close a file. The close() method can be called more than once and if any operation is performed on a closed file it raises a ValueError. The below code shows a simple use of close() method to close an opened file.

Example: Read and close the file using Python

Python3

# open the file using open() function
file = open("sample.txt")
   
# Reading from file
print(file.read())
 
# closing the file
file.close()
                      
                       

Now if we try to perform any operation on a closed file like shown below it raises a ValueError: 

Python3

# open the file using open() function
file = open("sample.txt")
   
# Reading from file
print(file.read())
 
# closing the file
file.close()
 
# Attempt to write in the file
file.write(" Attempt to write on a closed file !")
                      
                       

Output:

ValueError: I/O operation on closed file.


Next Article
How to delete from a pickle file in Python?

R

RajuKumar19
Improve
Article Tags :
  • Python
  • Write From Home
  • python-file-handling
Practice Tags :
  • python

Similar Reads

  • How to delete from a pickle file in Python?
    Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert a python object (list, dic
    3 min read
  • How to delete a CSV file in Python?
    In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column. Ap
    2 min read
  • How to copy file in Python3?
    Prerequisites: Shutil When we require a backup of data, we usually make a copy of that file. Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Here we will learn how to copy a file using Pyt
    2 min read
  • Open a File in Python
    Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, each line of text is terminated with a special character called EOL
    6 min read
  • How to delete data from file in Python
    When data is no longer needed, it’s important to free up space for more relevant information. Python's file handling capabilities allow us to manage files easily, whether it's deleting entire files, clearing contents or removing specific data. For more on file handling, check out: File Handling in P
    3 min read
  • How To Read .Data Files In Python?
    Unlocking the secrets of reading .data files in Python involves navigating through diverse structures. In this article, we will unravel the mysteries of reading .data files in Python through four distinct approaches. Understanding the structure of .data files is essential, as their format may vary w
    4 min read
  • How to Unpack a PKL File in Python
    Unpacking a PKL file in Python is a straightforward process using the pickle module. It allows you to easily save and load complex Python objects, making it a useful tool for many applications, especially in data science and machine learning. However, always be cautious about the security implicatio
    3 min read
  • How to make HTML files open in Chrome using Python?
    Prerequisites: Webbrowser HTML files contain Hypertext Markup Language (HTML), which is used to design and format the structure of a webpage. It is stored in a text format and contains tags that define the layout and content of the webpage. HTML files are widely used online and displayed in web brow
    2 min read
  • How to Split a File into a List in Python
    In this article, we are going to see how to Split a File into a List in Python.  When we want each line of the file to be listed at consecutive positions where each line becomes an element in the file, the splitlines() or rstrip() method is used to split a file into a list. Let's see a few examples
    5 min read
  • How to open two files together in Python?
    Prerequisites: Reading and Writing text files in Python Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files. An arbitrary number of files can be opened
    2 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