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:
File Mode in Python
Next article icon

File Mode in Python

Last Updated : 04 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, the file mode specifies the purpose and the operations that can be performed on a file when it is opened. When you open a file using the open() function, you can specify the file mode as the second argument.

Different File Mode in Python

Below are the different types of file modes in Python along with their description:

Mode

Description

‘r’Open text file for reading. Raises an I/O error if the file does not exist.
‘r+’Open the file for reading and writing. Raises an I/O error if the file does not exist.
‘w’Open the file for writing. Truncates the file if it already exists. Creates a new file if it does not exist.
‘w+’Open the file for reading and writing. Truncates the file if it already exists. Creates a new file if it does not exist.
‘a’Open the file for writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist.
‘a+’Open the file for reading and writing. The data being written will be inserted at the end of the file. Creates a new file if it does not exist.
‘rb’Open the file for reading in binary format. Raises an I/O error if the file does not exist.
‘rb+’Open the file for reading and writing in binary format. Raises an I/O error if the file does not exist.
‘wb’Open the file for writing in binary format. Truncates the file if it already exists. Creates a new file if it does not exist.
‘wb+’Open the file for reading and writing in binary format. Truncates the file if it already exists. Creates a new file if it does not exist.
‘ab’Open the file for appending in binary format. Inserts data at the end of the file. Creates a new file if it does not exist.
‘ab+’Open the file for reading and appending in binary format. Inserts data at the end of the file. Creates a new file if it does not exist.

File Mode in Python

Below are some of the file modes in Python:

Read Mode ('r') in Python

This mode allows you to open a file for reading only. If the file does not exist, it will raise a FileNotFoundError.

example.txt

Hello Geeks

Example:

In this example, a file named 'example.txt' is opened in read mode ('r'), and its content is read and stored in the variable 'content' using a 'with' statement, ensuring proper resource management by automatically closing the file after use.

Python3
with open('example.txt', 'r') as file:     content = file.read() 

Output:

Hello Geeks

Write Mode ('w') in Python

This mode allows you to open a file for writing only. If the file already exists, it will truncate the file to zero length. If the file does not exist, it will create a new file.

example.txt

Hello, world!

Example:

In this example, a file named 'example.txt' is opened in write mode ('w'), and the string 'Hello, world!' is written into the file.

Python3
with open('example.txt', 'w') as file:     file.write('Hello, world!') 

Output:

Hello, world!

Note - If you were to open the file "example.txt" after running this code, you would find that it contains the text "Hello, world!".

Append Mode ('a') in Python

This mode allows you to open a file for appending new content. If the file already exists, the new content will be added to the end of the file. If the file does not exist, it will create a new file.

example.txt

Hello, World! This is a new line

Example:

In this example, a file named 'example.txt' is opened in append mode ('a'), and the string '\nThis is a new line.' is written to the end of the file.

Python3
with open('example.txt', 'a') as file:     file.write('\nThis is a new line.') 

Output:

Hello, World! This is a new line

The code will then write the string "\nThis is a new line." to the file, appending it to the existing content or creating a new line if the file is empty.

Binary Mode ('b') in Python

This mode use in binary files, such as images, audio files etc. Its always used by combined with read (`'rb'`) or write ('wb') modes.

Example:

In this example, a file named 'image.png' is opened in binary read mode ('rb'). The binary data is read from the file using the 'read()' method and stored in the variable 'data'.

Python3
with open('image.png', 'rb') as file:     data = file.read()     # Process the binary data 

Read and Write Mode ('r+') in Python

This mode allows you to open a file for both reading and writing. The file pointer will be positioned at the beginning of the file. If the file does not exist, it will raise a FileNotFoundError.

example.txt

This is a new line. Initial content.
Python3
with open('example.txt', 'r+') as file:     content = file.read()     file.write('\nThis is a new line.') 

Output:

If the initial contents of "example.txt" we are "Initial content.", after running this code, the new content of the file would be:

This is a new line. Initial content.

Write and Read Mode ('w+') in Python

This mode allows you to open a file for both reading and writing. If the file already exists, it will truncate the file to zero length. If the file does not exist, it will create a new file.

example.txt

Hello, world!

Example:

In this example, a file named 'example.txt' is opened in write and read mode ('w+').

Python3
with open('example.txt', 'w+') as file:     file.write('Hello, world!')     file.seek(0)     content = file.read() 

Output:

Therefore, the output of this code will be the string "Hello, world!". Since the file was truncated and the pointer was moved to the beginning before reading, the contents of the file will be exactly what was written to it. So, content will contain the string "Hello, world!".

Hello, world!

Next Article
File Mode in Python

A

anurag702
Improve
Article Tags :
  • Python
  • python-file-handling
Practice Tags :
  • python

Similar Reads

    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
    File Objects in Python
    A file object allows us to use, access and manipulate all the user accessible files. One can read and write any such files. When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation is not defined for some reason, like seek()
    6 min read
    File Handling in Python
    File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
    7 min read
    fileinput.input() in Python
    With the help of fileinput.input() method, we can get the file as input and can be used to update and append the data in the file by using fileinput.input() method. Python fileinput.input() Syntax Syntax : fileinput.input(files) Parameter : fileinput module in Python has input() for reading from mul
    2 min read
    Python open() Function
    The Python open() function is used to open internally stored files. It returns the contents of the file as Python objects. Python open() Function SyntaxThe open() function in Python has the following syntax: Syntax: open(file_name, mode)  Parameters: file_name: This parameter as the name suggests, i
    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