This guide explains file modes: r, w, a, x, b, and + through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
File mode r reads an existing file, w truncates or creates one, a appends, x exclusively creates a new one, b enables binary data, and + allows both reading and writing.
When and Why to Use It
The following example focuses on a practical use of File Modes: r, w, a, x, b, and +.
Step-by-Step Example
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
file_path = Path(directory) / "notes.txt"
with file_path.open("x", encoding="utf-8") as output_file:
output_file.write("First\n")
with file_path.open("a", encoding="utf-8") as output_file:
output_file.write("Second\n")
print(file_path.read_text(encoding="utf-8"))
Understanding the Example
Exclusive create prevents accidental overwrite of a preexisting notes.txt. Append adds a second line without discarding the first.
Expected Output
First
Second
Important Behavior and Edge Cases
Using w+ or r+ without understanding the file cursor can overwrite existing bytes. Plan whether you need read, write or append first.
Try It Yourself
Explain the difference between wb and w for writing a PNG file versus a text note.
For file examples, use a dedicated practice directory or a temporary directory. Make sure you understand whether a call reads, creates, overwrites or appends before using it on important files.
Common Beginner Mistakes
- Using w+ or r+ without understanding the file cursor can overwrite existing bytes. Plan whether you need read, write or append first.
- Assuming the current working directory, encoding, filesystem contents or file permissions will be identical on every computer.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- File mode r reads an existing file, w truncates or creates one, a appends, x exclusively creates a new one, b enables binary data, and + allows both reading and writing.
- Exclusive create prevents accidental overwrite of a preexisting notes.txt.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.