File Handling
Binary Files
Reading and writing non-text data (images, audio, serialized objects) using binary mode and the struct module for precise byte-level control.
Interview: Tests understanding of bytes vs strings, encoding, and low-level data manipulation — common in systems programming interviews.
Binary files store data as raw bytes rather than encoded text. Python handles binary data using the bytes and bytearray types, and files must be opened in binary mode ('rb', 'wb', 'ab') to prevent any text encoding/decoding.
Binary vs Text Mode
- Text mode ('r', 'w'): Python decodes bytes to str using an encoding (default: UTF-8). Line endings are translated ( → on Windows).
- Binary mode ('rb', 'wb'): Returns raw bytes objects. No encoding/decoding, no line-ending translation.
- Key difference: Text mode returns
str, binary mode returnsbytes - Always use binary mode for: images, audio, video, executables, serialized data, network protocols
Bytes and Bytearray
bytes— immutable sequence of integers (0-255). Created withb"hello"orbytes()bytearray— mutable version of bytes. Supports item assignment and in-place modificationmemoryview— zero-copy view into bytes for efficient slicing of large binary data- Convert between str and bytes using
.encode()and.decode()
The struct Module
The struct module packs and unpacks binary data according to format strings:
struct.pack(format, values)— converts Python values to bytesstruct.unpack(format, bytes)— converts bytes back to Python values- Format codes:
i(int32),f(float),d(double),s(string),H(uint16) - Byte order:
<(little-endian),>(big-endian),=(native)
Interview Insight
Know the difference between bytes and str, and when to use each. Interviewers may ask about endianness, struct packing, or how to efficiently process large binary files (hint: read in chunks, use memoryview).
Use Cases
Image/audio/video processing — reading and manipulating media files
Network protocols — parsing binary packet formats
File format parsing — reading BMP, WAV, ZIP headers
Serialization — pickle, marshal for Python object persistence
Embedded systems — communicating with hardware using binary protocols
Common Mistakes
Opening binary files in text mode — causes encoding errors or data corruption
Reading entire large binary files into memory — use chunked reading instead
Confusing bytes indexing (returns int) with bytes slicing (returns bytes)
Forgetting byte order (endianness) when using struct — use < or > prefix
Trying to write str to a binary-mode file — must encode to bytes first