Python Mastery – From Basics to Brilliance / File Handling

File Modes in Python

Python offers different file modes for interacting with files, depending on whether you want to read, write, append, or create new files. These modes are passed as strings to the open() function.

open(filename, mode)

📖 r – Read Mode

🔍 Purpose:

Opens a file for reading only.

The file must exist, or Python will raise an error.

📌 Syntax:

f = open("example.txt", "r")

🧪 Example:

# Assume example.txt contains: Hello World
f = open("example.txt", "r")
print(f.read())
f.close(
Hello World

⚠️ Note: Raises FileNotFoundError if the file doesn't exist.


✍️ w – Write Mode

🧹 Purpose:

Opens a file for writing.

Overwrites the file if it exists, or creates a new file.

📌 Syntax:

f = open("example.txt", "w")

🧪 Example:

f = open("example.txt", "w")
f.write("New content")
f.close()
New content

The contents of example.txt now become:

⚠️ Warning: Existing file content is erased.


➕ a – Append Mode

📄 Purpose:

Opens the file for appending.

Data is written at the end of the file, preserving existing content.

📌 Syntax:

f = open("example.txt", "a")

🧪 Example:

f = open("example.txt", "a")
f.write("\\nAppended line")
f.close()

If original file had:

New content

It becomes:

New content
Appended line

🛑 x – Exclusive Creation Mode

🚫 Purpose:

Creates a new file. If the file already exists, it raises a FileExistsError.

📌 Syntax:

f = open("newfile.txt", "x")

🧪 Example:

f = open("unique.txt", "x")
f.write("This file is newly created.")
f.close()

A new file unique.txt is created with:

This file is newly created.

⚠️ Note: If unique.txt already exists, Python throws:

FileExistsError: [Errno 17] File exists: 'unique.txt'

💾 b – Binary Mode (with r, w, a)

📦 Purpose:

Used when working with binary files like images, videos, or PDFs.

You must combine it with another mode (rb, wb, etc.)

📌 Syntax:

f = open("image.png", "rb")  # Read binary
f = open("video.mp4", "wb")  # Write binary

🧪 Example:

# Copy an image in binary mode
f1 = open("source.png", "rb")
f2 = open("copy.png", "wb")
f2.write(f1.read())
f1.close()
f2.close()

⚠️ Note: Always use binary mode when working with non-text files.

A binary copy of source.png is created as copy.png.


🧪 Combining Modes

You can combine file modes like:

  • "rb" – Read binary

  • "wb" – Write binary

  • "ab" – Append binary

  • "r+" – Read and write

  • "w+" – Write and read (file overwritten)

  • "a+" – Append and read