-
Hajipur, Bihar, 844101
In Python, file modes determine how a file is opened and interacted with. Choosing the correct mode is crucial for reading, writing, appending, or creating files safely. Each mode has a specific behavior that impacts data preservation and program execution.
This tutorial covers all file modes, their usage, practical examples, and best practices for efficient file handling.
When you open a file in Python using the open() function, you must specify the mode. The mode defines whether the file is:
Opened for reading
Opened for writing
Opened for appending
Created only if it doesn’t exist
Syntax:
file = open("filename", "mode")
filename – Name of the file
mode – File mode ('r', 'w', 'a', 'x', etc.)
'r' – Read ModeDefault mode if no mode is specified
Opens the file for reading only
Raises FileNotFoundError if the file does not exist
Example:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Use 'r' when you only need to access file content
Does not allow writing or modifying the file
'w' – Write ModeOpens the file for writing
If the file exists, its contents are overwritten
If the file does not exist, a new file is created
Example:
file = open("example.txt", "w")
file.write("Python file handling in write mode.\n")
file.close()
Use 'w' to create new files or overwrite existing files
Important: Existing data will be lost
'a' – Append ModeOpens the file for appending
New data is added to the end of the file
Does not overwrite existing content
Creates a new file if it does not exist
Example:
file = open("example.txt", "a")
file.write("This line will be appended.\n")
file.close()
Ideal for logs, records, or incremental data storage
Ensures existing data is preserved
'x' – Create ModeOpens the file for exclusive creation
Creates a new file only if it does not exist
Raises FileExistsError if the file already exists
Example:
file = open("newfile.txt", "x")
file.write("This file is created using 'x' mode.\n")
file.close()
Use 'x' to prevent overwriting important files
Useful in automation scripts where accidental overwriting must be avoided
Python also supports binary file modes for non-text files like images or PDFs:
| Mode | Description |
|---|---|
rb |
Read binary |
wb |
Write binary |
ab |
Append binary |
xb |
Create binary |
Example: Writing binary data:
data = b"Binary data example."
with open("example.bin", "wb") as file:
file.write(data)
Text modes (r, w, a, x) – Work with strings
Binary modes (rb, wb, ab, xb) – Work with bytes
Use the appropriate mode depending on the file type
Using the with statement ensures files are automatically closed:
with open("example.txt", "w") as file:
file.write("File handling with context manager.\n")
Prevents resource leaks
Recommended for all file operations
| Mode | Purpose | Behavior |
|---|---|---|
r |
Read | Access file content, error if file does not exist |
w |
Write | Overwrites existing content, creates file if not exists |
a |
Append | Adds data to the end, preserves existing content |
x |
Create | Creates a new file, error if file exists |
rb |
Read binary | Reads bytes from a file |
wb |
Write binary | Writes bytes to a file, overwrites existing file |
ab |
Append binary | Adds bytes at the end of the file |
xb |
Create binary | Creates new binary file, error if exists |
Read a file using 'r' mode:
with open("example.txt", "r") as file:
print(file.read())
Write a file using 'w' mode:
with open("example.txt", "w") as file:
file.write("This is written in write mode.\n")
Append text using 'a' mode:
with open("example.txt", "a") as file:
file.write("Appending new text.\n")
Create a new file using 'x' mode:
with open("newfile.txt", "x") as file:
file.write("File created using 'x' mode.\n")
Write binary data using 'wb':
data = b"Example binary data"
with open("data.bin", "wb") as file:
file.write(data)
Read binary file using 'rb':
with open("data.bin", "rb") as file:
content = file.read()
print(content)
Append binary data using 'ab':
data = b"\nAdditional bytes"
with open("data.bin", "ab") as file:
file.write(data)
Prevent overwriting using 'x' mode:
try:
with open("example.txt", "x") as file:
file.write("Safe creation.\n")
except FileExistsError:
print("File already exists!")
Iterate over a file opened in 'r' mode:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Writing multiple lines safely:
lines = ["Line 1\n", "Line 2\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
Python file modes determine how files are opened and manipulated:
r – Read only
w – Write, overwrites if file exists
a – Append, preserves content
x – Create exclusively, error if exists
Binary modes handle non-text data like images or PDFs. Always use context managers (with) to ensure safe opening and closing of files.
Mastering file modes is essential for data management, automation, and safe file operations, forming the foundation of real-world Python applications.
Q1. Write a Python program to open a file in read ("r") mode and print its content.
Q2. Write a Python program to write "Good Morning" to a file using "w" mode (overwrites existing content).
Q3. Write a Python program to append a message to a file using "a" mode without deleting previous content.
Q4. Write a Python program to create a file using "x" mode and add some text (error if file already exists).
Q5. Write a Python program to handle error if a file does not exist in "r" mode using try-except.
Q6. Write a Python program to use "wb" mode to write binary data like b'010101' to a file.
Q7. Write a Python program to open a text file using "rt" mode and read its content.
Q8. Write a Python program to try opening a non-existing file in "x" mode and handle the error.
Q9. Write a Python program to check what happens if "w" mode is used on an existing file (observe overwritten content).
Q10. Write a Python program to read image data using "rb" mode and print the type of the data (should be bytes).