File Handling
File Modes
Understanding r, w, a, b, x, and + modes
Interview: File access — tests understanding of mode combinations and when each is appropriate
File modes control how a file is opened — whether you can read, write, append, or use binary mode. Understanding all mode combinations is essential for correct file operations.
Mode Reference
'r': Read (default) — error if file doesn't exist'w': Write — creates/truncates file'a': Append — creates if missing, writes at end'x': Exclusive create — error if file exists'b': Binary mode (combine with r/w/a)'t': Text mode (default)'+': Update (read AND write, combine with r/w/a)
Interview Tip
Know the difference between 'w' and 'a': 'w' truncates the file (deletes existing content), 'a' preserves it and writes at the end. Also know 'x' for safe file creation.
Use Cases
Reading data files (r mode)
Creating new output files (w mode)
Logging to existing files (a mode)
Safe file creation without overwriting (x mode)
Working with images, audio, and other binary data (b mode)
Common Mistakes
Using w mode when you want to append — it truncates existing content!
Not knowing x mode exists for safe exclusive file creation
Opening binary files in text mode (no encoding conversion needed)
Forgetting that a mode always writes at end (even after read)
Using r+ without seeking — writes happen at current position