- Learning Objectives
- Prerequisites
- Introduction
- What are File Modes?
- Why are File Modes Required?
- Types of File Modes
- Text Modes
- Binary Modes
- File Pointer Behavior
- File Mode Comparison
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand file modes.
- Differentiate read, write, append, and create modes.
- Work with update modes.
- Understand binary file modes.
- Learn file pointer behavior.
- Select the correct mode for different scenarios.
Before learning this chapter, you should know:
- File Handling Basics
- open() Function
- Reading and Writing Files
When opening a file,
Python needs to know how the file will be used.
For example,
- Read existing data
- Write new data
- Append data
- Create a new file
- Read and write together
This is specified using File Modes.
A File Mode specifies the purpose for which a file is opened.
It tells Python what operations are allowed on the file.
File modes tell Python how to open and use a file.
Different operations require different permissions.
For example:
- Reading requires read permission.
- Writing requires write permission.
- Appending requires append permission.
Using the wrong mode can lead to errors or accidental data loss.
| Mode | Description |
|---|---|
r |
Read |
w |
Write |
a |
Append |
x |
Create |
r+ |
Read and Write |
w+ |
Write and Read |
a+ |
Append and Read |
rb |
Read Binary |
wb |
Write Binary |
ab |
Append Binary |
Used for reading an existing file.
If the file does not exist,
Python raises
FileNotFoundErrorExample
file = open("student.txt", "r")Used for writing data.
If the file exists,
its previous contents are removed.
If it does not exist,
Python creates a new file.
Example
file = open("student.txt", "w")Adds new data to the end of the file.
Existing data remains unchanged.
Example
file = open("student.txt", "a")Creates a new file.
If the file already exists,
Python raises
FileExistsErrorExample
file = open("student.txt", "x")Allows both reading and writing.
The file must already exist.
Example
file = open("student.txt", "r+")Allows reading and writing.
Existing content is erased before writing.
Example
file = open("student.txt", "w+")Allows appending and reading.
Existing content is preserved.
Example
file = open("student.txt", "a+")Binary files contain non-text data.
Examples
- Images
- Videos
- Audio
- PDF Documents
- Executables
Binary modes include:
rb
wb
ab
Example
file = open("photo.jpg", "rb")Whenever a file is opened,
Python maintains a file pointer.
The file pointer indicates the current reading or writing position.
Example
Python
↓
File Opened
↓
Pointer at Beginning
↓
Read()
↓
Pointer Moves Forward
| Mode | Read | Write | Create File | Overwrite | Append |
|---|---|---|---|---|---|
| r | ✅ | ❌ | ❌ | ❌ | ❌ |
| w | ❌ | ✅ | ✅ | ✅ | ❌ |
| a | ❌ | ✅ | ✅ | ❌ | ✅ |
| x | ❌ | ✅ | ✅ (New Only) | ❌ | ❌ |
| r+ | ✅ | ✅ | ❌ | ❌ | ❌ |
| w+ | ✅ | ✅ | ✅ | ✅ | ❌ |
| a+ | ✅ | ✅ | ✅ | ❌ | ✅ |
Program Starts
↓
open(file, mode)
↓
Operating System Checks Mode
↓
Permission Granted
↓
File Object Created
↓
Operation Performed
↓
close()
↓
Program Ends
- Controls file access.
- Prevents accidental operations.
- Supports different use cases.
- Works with text and binary files.
- Improves application safety.
- Use the least permissive mode required.
- Avoid
wunless overwriting is intended. - Use
afor logs and reports. - Use
xwhen creating new files safely. - Use binary modes for non-text files.
Using w instead of a.
This removes existing content.
Opening a binary file using text mode.
Using r when the file does not exist.
Raises
FileNotFoundErrorUsing x when the file already exists.
Raises
FileExistsErrorfile = open("student.txt", "r")
print(file.read())
file.close()file = open("student.txt", "w")
file.write("Python")
file.close()file = open("student.txt", "a")
file.write("\nAdvanced Python")
file.close()file = open("newfile.txt", "x")
file.close()file = open("student.txt", "r+")
print(file.read())
file.write("\nNew Record")
file.close()file = open("student.txt", "w+")
file.write("Python")
file.seek(0)
print(file.read())
file.close()seek(0) moves the file pointer back to the beginning before reading.
file = open("student.txt", "a+")
file.write("\nNew Line")
file.seek(0)
print(file.read())
file.close()file = open("photo.jpg", "rb")
data = file.read()
print(type(data))
file.close()<class 'bytes'>
file = open("sample.bin", "wb")
file.write(b"Python")
file.close()file = open("sample.bin", "ab")
file.write(b"123")
file.close()Program Starts
↓
Choose File Mode
↓
Open File
↓
File Pointer Created
↓
Perform Operation
↓
Close File
↓
Program Ends
Python Program
│
├── File Object
│ │
│ ├── Mode : r
│ ├── Pointer
│ └── Data
│
└── student.txt
A file mode specifies how a file is opened and what operations are permitted.
rThe file is opened for writing.
If it exists, its contents are overwritten.
If it does not exist, a new file is created.
woverwrites existing data.apreserves existing data and appends new data.
xIt allows both reading and writing without automatically overwriting the file.
It moves the file pointer to the beginning of the file.
rbwbab
FileExistsErrorFileNotFoundError- Open a file using every file mode.
- Compare
wanda. - Read and write using
r+. - Use
seek()after writing. - Read a binary file.
r→ Readw→ Write (Overwrite)a→ Appendx→ Create New Filer+→ Read + Writew+→ Write + Reada+→ Append + Readrb→ Read Binarywb→ Write Binaryab→ Append Binary
In this chapter, we learned:
- File Modes
- Text Modes
- Binary Modes
- File Pointer
- File Mode Comparison
- Practical Programs
- Advantages
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision