Python

In Python, File Modes define the specific permissions and actions allowed when opening a connection to a file. Choosing the correct mode is critical because it determines whether you can read data, write new data, or if you will accidentally delete existing content.

1. Theoretical Overview

The "Mode" Concept

When you use the open() function, the second argument is the Mode String. It tells the operating system's file system how to handle the file pointer:

  • Where to start: At the beginning or the end of the file?

  • Permission: Read-only, Write-only, or both?

  • File Type: Text (t) or Binary (b)?

Key Categories of Modes

  1. Read (r): The file pointer is placed at the beginning. If the file doesn't exist, Python throws a FileNotFoundError.

  2. Write (w): Creates a new file. If the file already exists, it truncates (wipes out) everything inside before writing.

  3. Append (a): The file pointer is at the end. If the file exists, new data is added after the current content.

  4. Create (x): Exclusive creation. It fails if the file already exists (preventing accidental overwrites).

2. The Comprehensive Mode Table

ModeDescriptionPointer PositionExists?No File?
rRead OnlyStartOKError
wWrite OnlyStartOverwritesCreates
aAppend OnlyEndOKCreates
r+Read & WriteStartOKError
w+Write & ReadStartOverwritesCreates
a+Append & ReadEndOKCreates
rb / wbBinary ModesStartN/AVaries

3. Code Implementation

A. The "Plus" Modes (r+ vs w+)

The + modes are used when you need to perform both reading and writing on the same file object.

Python
# 'r+' allows reading and writing without wiping the file
with open("data.txt", "w") as f: f.write("Original Content")

with open("data.txt", "r+") as file:
    content = file.read() # Reads the original
    print(f"Read: {content}")
    file.write("\nNew Update") # Adds at the current pointer position

B. Exclusive Creation (x)

Use this when it is critical that you don't overwrite an existing file (like generating a unique report).

Python
try:
    with open("secure_report.txt", "x") as file:
        file.write("Confidential Data")
except FileExistsError:
    print("Error: This file already exists! Choose a different name.")

C. Binary Modes (rb, wb)

Used for non-text files like images, PDFs, or compiled data. Note that you must write "bytes" objects (b'').

Python
# Copying an image (binary read and binary write)
with open("logo.png", "rb") as source:
    img_data = source.read()

with open("logo_copy.png", "wb") as destination:
    destination.write(img_data)

4. Summary Table for Quick Reference

  • Use r for simple data extraction.

  • Use w for fresh logs or saving a new document.

  • Use a for continuous logs or chat histories.

  • Use b suffix for anything that isn't a .txt file.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now