Skip to content

Module 13 · File Handling — topic 6 of 15

File modes

Every open() mode explained: r, w, a, x, the + update modes, text versus binary (t and b), what each does to existing files, and choosing the safest mode.

Beginner 8 min read·Lesson 199 of 306 in Python Programming

Learning objectives

  • Choose the correct mode for a task
  • Explain what each mode does to existing files
  • Use binary and update modes

Definition

The mode string passed to open() decides whether the file is read, written, appended or created, whether existing content is kept, and whether data is text (str) or binary (bytes).

Introduction

One letter in open() decides whether your file is read, extended or wiped. Knowing the modes by heart prevents painful accidents.

Why it matters

Picking the right mode expresses intent and protects data: "x" refuses to overwrite, "a" never erases, "r" can't modify.

Detailed explanation

"r" — read (default). The file must exist. Position starts at the beginning.

"w" — write. Creates the file or truncates it to empty.

"a" — append. Creates the file if needed; writes always go to the end.

"x" — exclusive creation. Creates a new file and fails with FileExistsError if it already exists.

Adding + allows both reading and writing: "r+" (file must exist, no truncation), "w+" (truncates), "a+" (writes at the end).

Adding b selects binary mode ("rb", "wb", "ab"): data is bytes and no encoding or newline translation happens. t (text) is the default.

With update modes, f.seek(offset) moves the position and f.truncate() cuts the file at the current position.

Syntax

Python
open(path, "r") # read text
open(path, "w") # write (truncate)
open(path, "a") # append
open(path, "x") # create new only
open(path, "rb") # read bytes
open(path, "r+") # read and write
  • r, w, a, x choose the action.
  • + adds the other direction.
  • b switches to bytes.

Code examples

"x" refuses to overwrite

Python
with open("new.txt", "x", encoding="utf-8") as f:
f.write("created")
try:
open("new.txt", "x", encoding="utf-8")
except FileExistsError:
print("x refuses to overwrite")
with open("new.txt", encoding="utf-8") as f:
print(f.read())
Output
x refuses to overwrite
created

Updating in place with "r+"

Python
with open("count.txt", "w", encoding="utf-8") as f:
f.write("0")
for _ in range(3):
with open("count.txt", "r+", encoding="utf-8") as f:
n = int(f.read())
f.seek(0)
f.write(str(n + 1))
f.truncate()
with open("count.txt", encoding="utf-8") as f:
print(f.read())
Output
3

More examples

Copying a binary file in chunks

Python
data = bytes(range(256)) * 40 # 10,240 bytes
with open("src.bin", "wb") as f:
f.write(data)
chunks = 0
with open("src.bin", "rb") as src, open("copy.bin", "wb") as dst:
while chunk := src.read(4096):
dst.write(chunk)
chunks += 1
with open("copy.bin", "rb") as f:
copied = f.read()
print(len(copied), chunks, copied == data)
Output
10240 3 True

Step-by-step explanation

  • Binary modes read and write bytes exactly, which is essential for images, archives and other non-text files.
  • Reading 4,096 bytes at a time keeps memory use small, even for huge files.
  • The walrus operator stops the loop when read returns empty bytes at the end of the file.

Expected output

Running “Copying a binary file in chunks” prints exactly:

TextOutput
10240 3 True

Practical applications

  • "x" for creating output files without clobbering previous results.
  • "rb"/"wb" for images, PDFs and downloads.

Best practices

  • Use the least powerful mode that does the job.
  • Use "x" when overwriting would be a mistake.
  • Use binary mode for anything that isn't text.

Common mistakes

"w+" to read existing content

Avoid

with open("data.txt", "w+") as f:
print(f.read())

Prefer

with open("data.txt", "r+", encoding="utf-8") as f:
print(f.read())

"w+" truncates first, so there is nothing to read.

Text mode for binary data

Avoid

open("photo.jpg", "r")

Prefer

open("photo.jpg", "rb")

Decoding image bytes as text fails or corrupts the data.

Important notes

  • shutil.copyfile performs chunked copying for you.

Key takeaways

  • r reads, w truncates, a appends, x creates new.
  • + adds reading or writing.
  • b switches to bytes.

Try it yourself

  1. 1
    Write a function that saves output to a new file name (out1.txt, out2.txt, …) using "x" to avoid overwriting.
  2. 2
    Compare two binary files chunk by chunk and report whether they are identical.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhich mode creates a new file but fails if the file already exists?
Practise this topic