Skip to content
๐Ÿ“‚ Python File Modes

๐Ÿ“‚ 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

ModeReadWriteTruncateCreatePointerNotes
'r'โœ…โŒโŒโŒStartFails if file doesn’t exist
'r+'โœ…โœ…โŒโŒStartRead/write, no truncation
'w'โŒโœ…โœ…โœ…StartOverwrites file
'w+'โœ…โœ…โœ…โœ…StartRead/write with truncation
'a'โŒโœ…โŒโœ…EndAppends only
'a+'โœ…โœ…โŒโœ…EndRead/append, pointer at end
'x'โŒโœ…โŒโœ…StartFails if file exists

๐Ÿงฌ Binary Mode Variants

ModeReadWriteTruncateCreatePointerNotes
'rb'โœ…โŒโŒโŒStartBinary read
'rb+'โœ…โœ…โŒโŒStartBinary read/write
'wb'โŒโœ…โœ…โœ…StartBinary write, overwrites
'wb+'โœ…โœ…โœ…โœ…StartBinary read/write with truncation
'ab'โŒโœ…โŒโœ…EndBinary append only
'ab+'โœ…โœ…โŒโœ…EndBinary 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::AccessMatrix
  • Audit::TruncationRisk
  • Pointer::Start vs End
  • Binary::EncodingImplications
  • Resilience::ExistenceCheck
  • Vault::OpenModeAnchors

๐Ÿงฉ Want to scaffold a module comparing file pointer behavior, or benchmark read/write performance across modes and buffer sizes?

Last updated on