File Modes in Python
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.
"r" — read (the default)
Opens an existing file for reading — raises an error if the file doesn’t exist.
"w" — write
Creates a new file or completely overwrites an existing one, erasing any prior contents.
"a" — append
Adds new content to the end of a file, without erasing what’s already there, creating the file if needed.
"x" — exclusive creation
Creates a new file but raises an error if one already exists, guarding against accidentally overwriting something.
Adding "b" switches to binary mode
"rb" or "wb" work with non-text files like images, rather than the default text mode.
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())Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.