๐ Python File Modes
๐ Motivation
File modes define how Python interacts with filesโwhether reading, writing, appending, or combining operations. Understanding these modes is essential for safe I/O, audit clarity, and avoiding silent data loss.
๐งฉ Text Mode Variants
| Mode | Read | Write | Truncate | Create | Pointer | Notes |
|---|---|---|---|---|---|---|
'r' | โ | โ | โ | โ | Start | Fails if file doesn’t exist |
'r+' | โ | โ | โ | โ | Start | Read/write, no truncation |
'w' | โ | โ | โ | โ | Start | Overwrites file |
'w+' | โ | โ | โ | โ | Start | Read/write with truncation |
'a' | โ | โ | โ | โ | End | Appends only |
'a+' | โ | โ | โ | โ | End | Read/append, pointer at end |
'x' | โ | โ | โ | โ | Start | Fails if file exists |
๐งฌ Binary Mode Variants
| Mode | Read | Write | Truncate | Create | Pointer | Notes |
|---|---|---|---|---|---|---|
'rb' | โ | โ | โ | โ | Start | Binary read |
'rb+' | โ | โ | โ | โ | Start | Binary read/write |
'wb' | โ | โ | โ | โ | Start | Binary write, overwrites |
'wb+' | โ | โ | โ | โ | Start | Binary read/write with truncation |
'ab' | โ | โ | โ | โ | End | Binary append only |
'ab+' | โ | โ | โ | โ | End | Binary read/append |
๐งฌ Feature Definitions
๐ Read
- Grants permission to access file contents via
.read(),.readline(), etc. - If omitted, read operations raise
io.UnsupportedOperation.
โ๏ธ Write
- Grants permission to modify file contents via
.write(),.writelines(). - If omitted, write operations raise
io.UnsupportedOperation.
๐งจ Truncate
- Clears the file contents upon opening.
- Enabled in
'w','w+','wb','wb+'.
๐ Create
- Creates the file if it doesnโt exist.
- Enabled in
'w','w+','a','a+','x'.
๐ Pointer
- Defines where the file cursor starts:
'r','w','w+'โ Start of file'a','a+'โ End of file
- Affects
.seek()and.tell()behavior.
๐ Mode Behavior Summary
'r'/'rb': Read-only. File must exist.'r+'/'rb+': Read/write. No truncation. File must exist.'w'/'wb': Write-only. Truncates file. Creates if missing.'w+'/'wb+': Read/write. Truncates file. Creates if missing.'a'/'ab': Append-only. Pointer at end. Creates if missing.'a+'/'ab+': Read/append. Pointer at end. Creates if missing.'x': Exclusive creation. Fails if file exists.
๐ง Vault Integration Flags
FileMode::AccessMatrixAudit::TruncationRiskPointer::Start vs EndBinary::EncodingImplicationsResilience::ExistenceCheckVault::OpenModeAnchors
๐งฉ Want to scaffold a module comparing file pointer behavior, or benchmark read/write performance across modes and buffer sizes?
Last updated on