Learn Python
>>> file_handling.file_modes

File Modes in Python

#concept

The mode passed to open() determines exactly how a file will be used — whether it's opened for reading, writing, or appending, and whether it's treated as text or raw binary data. Choosing the wrong mode is a common source of confusing errors, like accidentally erasing a file that was meant to be appended to.

#how it works
1

"r" — read (the default)

Opens an existing file for reading — raises an error if the file doesn’t exist.

2

"w" — write

Creates a new file or completely overwrites an existing one, erasing any prior contents.

3

"a" — append

Adds new content to the end of a file, without erasing what’s already there, creating the file if needed.

4

"x" — exclusive creation

Creates a new file but raises an error if one already exists, guarding against accidentally overwriting something.

5

Adding "b" switches to binary mode

"rb" or "wb" work with non-text files like images, rather than the default text mode.

#example
with open("log.txt", "w") as f:
f.write("First entry\n")
 
with open("log.txt", "a") as f:
f.write("Second entry\n")
 
with open("log.txt", "r") as f:
print(f.read())
Output
First entry
Second entry
1"w" mode creates log.txt fresh, writing the first entry — any prior content would have been erased.
2"a" mode reopens the same file and adds the second entry to the end, without touching what was already there.
3"r" mode reads the whole file back, showing both entries preserved in order, proving append didn't overwrite the first write.
#use cases
Choosing 'a' deliberately for an ever-growing log file, instead of accidentally erasing it with 'w' each run
Using 'x' to safely create a new file only when one doesn't already exist, avoiding accidental overwrites
Reaching for binary mode ('rb'/'wb') when working with images, audio, or any non-text file format
Debugging a mysteriously empty file, which is often caused by opening it with 'w' when 'a' or 'r' was actually intended

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.