CodeBlanks Logo Icon CodeBlanks

File modes

Learn modes 'r', 'w', 'a', 'b'.

All file modes

Basic modes: r read, w write (truncates), a append, x exclusive create (error if exists). Add + for read-write combinations: r+, w+, a+.

For binary data add b: rb, wb, ab. In binary mode data is read and written as bytes; no encoding parameter. Images, audio or compressed files are handled in binary mode.

Practice Append with a mode

First create the file with with open("diary.txt", "w", encoding="utf-8") as f: f.write("First line\n"). Then append with with open("diary.txt", "a", encoding="utf-8") as f: f.write("Second line\n"). Finally print the line count with with open("diary.txt", "r", encoding="utf-8") as f: print(len(f.readlines())).

Starter code

main.py
# w mode: write the first line
# a mode: append the second line
# r mode: print the line count

Sample solution

main.py
# w mode: write the first line
with open("diary.txt", "w", encoding="utf-8") as f:
    f.write("First line\n")
# a mode: append the second line
with open("diary.txt", "a", encoding="utf-8") as f:
    f.write("Second line\n")
# r mode: print the line count
with open("diary.txt", "r", encoding="utf-8") as f:
    print(len(f.readlines()))

Expected output

2

When to use binary mode?

Binary mode is enabled with the b suffix: rb, wb, ab. This mode is for non-text files like images, audio, video or compressed data. Data is read and written as bytes.

In binary mode the encoding parameter is not used; encoding only applies to text. If you accidentally open a text file in binary mode you get bytes back and see prefixes like b"\n" instead of \n.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which mode appends without truncating?

  • w
  • a Correct answer
  • r
  • x

Explanation: The a mode (append) adds to the end without truncating.

2 Complete the binary read mode

Question
f = open("image.png", "____")
data = f.read()
f.close()
Answer
f = open("image.png", "rb")
data = f.read()
f.close()

Explanation: rb is the binary read mode.

3 Match the mode suffixes

Term Meaning
b Binary data suffix
+ Read-write suffix
x Exclusive create
a Append

All lessons in Intermediate