File Modes

When working with files in Python, understanding file modes is essential. File modes determine how a file is opened and what operations you can perform on it: reading, writing, appending, or even updating. Choosing the correct file mode ensures your program behaves as expected and prevents data loss or corruption.

Before diving into the specifics, let's consider what happens when you open a file. Behind the scenes, Python communicates with the operating system to access the file, and the mode tells it whether you want to read the contents, overwrite them, add new data, or perform other operations.

Architecture of File Modes
Architecture of File Modes

Core File Modes in Python

Python’s built-in open() function accepts a mode argument which is a string that specifies the mode. Here are the fundamental modes you will encounter:

Basic File Modes
ModeDescription
rOpen for reading (default). The file must exist.
wOpen for writing. Creates a new file or truncates an existing file (empties it).
aOpen for appending. Creates the file if it doesn’t exist. Adds data to the end.
xCreate a new file and open it for writing. Fails if the file already exists.
bBinary mode. Used in combination with other modes for binary files (e.g., rb, wb).
tText mode (default). Used in combination with other modes (e.g., rt, wt).
+Open for updating (reading and writing).

Notice that some modes can be combined, for example, r+ opens a file for both reading and writing without truncating it, while w+ opens for reading and writing but truncates the file.

How to Choose the Right File Mode?

Choosing the correct mode depends on what you want to do:

  • Read existing data: Use r or rb.
  • Create or overwrite a file: Use w or wb.
  • Add data to the end of a file: Use a or ab.
  • Create a new file, but fail if it exists: Use x or xb.
  • Read and write: Use r+, w+, a+ (with or without b depending on binary or text).

💡 Remember

Text mode is the default. Binary mode is necessary when working with non-text files like images, videos, or any file that requires exact byte-level operations.

Detailed Explanation of Each Mode

r — Read Only

This is the default mode. When you open a file in read mode, Python expects the file to already exist. If it doesn’t, you’ll get a FileNotFoundError. You can only read data; writing is not allowed.

📌 Deep Dive: Reading a File

PYTHON
with open("example.txt", "r") as file:
    content = file.read()
print(content)
Output
Hello, this is an example file content.

w — Write (Overwrite)

Opening a file in write mode creates the file if it does not exist. If the file exists, it erases all existing content before writing new data. Use this mode when you want to start fresh or replace the file’s content.

📌 Deep Dive: Writing a File

PYTHON
with open("example.txt", "w") as file:
    file.write("New content replaces old content.")
Output
(File content is now replaced with the above text)

a — Append

The append mode opens the file and places the file pointer at the end so new data is added after existing content. The file is created if it doesn’t exist.

📌 Deep Dive: Appending to a File

PYTHON
with open("example.txt", "a") as file:
    file.write("
This line is appended.")
Output
(New line added at the end of the file)

x — Exclusive Creation

This mode is used to create a new file. If the file already exists, opening in x mode raises a FileExistsError. It’s a safe way to ensure you don’t accidentally overwrite existing files.

⚠️ Caution with x mode

Use x when you want to guarantee a new file is created. If the file exists, your program will halt unless you handle the exception.

+ — Update Mode (Read & Write)

Adding + to a mode opens the file for both reading and writing. The behavior depends on the base mode:

  • r+: Opens for reading and writing. File must exist. Does not truncate the file.
  • w+: Opens for reading and writing. Creates or truncates the file.
  • a+: Opens for reading and appending. Creates file if it does not exist. Writes are always at the end.

This is useful when you want to modify a file’s content without losing existing data unless you truncate it.

Text Mode vs Binary Mode

By default, Python opens files in text mode (t). This mode is suitable for files containing human-readable text. In text mode, Python automatically handles character encoding and newline conversions (e.g., converting to the appropriate system newline).

Binary mode (b) treats the file as a binary stream of bytes. This mode is necessary for non-text files like images, audio, video, or any file format where exact byte sequences must be preserved. In binary mode, no encoding or newline translation is done.

Text vs Binary Modes
AspectText Mode (t)Binary Mode (b)
Default modeYesNo
Handles encoding/decodingYesNo
Newline conversionYesNo
Data type returned by read()strbytes
Use caseText files (e.g., .txt, .py, .csv)Binary files (e.g., .jpg, .exe, .bin)

Common Combinations and Examples

Let’s look at some common file mode combinations and their typical use cases:

  • rt or r: Read text file (default).
  • rb: Read binary file.
  • wt or w: Write text file (overwrite).
  • wb: Write binary file (overwrite).
  • at or a: Append text file.
  • ab: Append binary file.
  • r+: Read and write text file.
  • w+: Write and read (overwrite) text file.
  • a+: Append and read text file.

📌 Deep Dive: Reading and Writing with r+ Mode

PYTHON
with open("example.txt", "r+") as file:
    content = file.read()
    print("Original content:")
    print(content)
    file.seek(0)  # Go back to the start
    file.write("Updated content!")
Output
Original content: Hello, this is an example file content.

In the example above, r+ lets us read the file, then reposition the pointer to the beginning with seek(0) and overwrite part or all of the content.

File Modes and Exceptions

Using file modes incorrectly can cause errors. Here are some common exceptions related to file modes:

  • FileNotFoundError — Trying to read (r) a file that does not exist.
  • FileExistsError — Trying to create (x) a file that already exists.
  • UnsupportedOperation — Trying to write to a file opened in read-only mode or vice versa.

⚠️ Handling File Exceptions

It’s good practice to handle these exceptions using try-except blocks to make your programs more robust and user-friendly.

Summary: Practical Tips for Using File Modes

  • Always know whether you want to read, write, append, or update before choosing a mode.
  • Use r when you only need to read existing files.
  • Use w to start fresh and overwrite files.
  • Use a to add new data without deleting old data.
  • Use x when you want to create a file only if it doesn’t exist.
  • Use + to combine reading and writing capabilities.
  • Don’t forget to specify binary mode (b) when dealing with non-text files.
  • Use with blocks to automatically close files and prevent resource leaks.

💡 Best Practice

Always open files using the with open(...) syntax. This ensures files are properly closed, even if errors occur.

Next Steps

Now that you understand file modes, try opening different files with various modes and experiment with reading, writing, and appending data. This hands-on practice will deepen your understanding and prepare you for more advanced file operations like working with CSVs, JSON, or binary data.