File Handling, Binary Data, Serialization & Directories
An authoritative reference manual on text/binary file I/O, OS file descriptors, the with context manager protocol, seek()/tell() pointers, pickle opcode serialization, zipfile compression, and os/shutil directory tools.
Persistence allows data to survive program termination by writing to disk storage. This chapter covers Operating System file descriptors, text vs binary stream modes, context managers, random file access, object serialization with pickle, ZIP compression, and directory handling.
7.1. 1. File I/O Mechanics, Text/Binary Files & Context Managers
Definition: Files are opened using `open(filename, mode)` to return an I/O stream object bound to an OS file descriptor; the `with` statement acts as a Context Manager guaranteeing automatic file closure.
Core Working Principles:
- File Access Modes: `'r'` (read), `'w'` (overwrite write), `'a'` (append write), `'b'` (binary mode flag e.g. `'rb'`, `'wb'`), `'+'` (read/write updating).
- Text vs Binary Files: Text files encode characters (UTF-8); Binary files handle raw unencoded byte streams without newline translation.
- Context Manager Protocol: Invokes `__enter__()` upon block entry and `__exit__()` upon exit, ensuring file handles are closed automatically even when unhandled exceptions occur!
Manual open()/close(): Like opening a room door manually—if you forget to close it or run away in a hurry (exception), the door stays wide open (memory leak / file lock)!
The with Statement: Like a spring-loaded automatic door—closes and locks the file handle securely behind you the moment you leave the room!
5-Marks Exam Scoring Points
- Always use the 'with open(...) as f:' pattern to guarantee resource cleanup.
- Binary mode ('rb', 'wb') bypasses text encoding/decoding transformations.
- File writing mode 'w' overwrites existing files; 'a' appends data to end.
7.2. 2. Random File Access, Pickle, Zipping & Directories
Definition: Random access positions the file pointer; Pickle serializes Python objects; zipfile manages compressed archives; os/shutil control directories.
Core Working Principles:
- File Pointer Control: `tell()` returns current byte offset; `seek(offset, whence)` moves pointer (`whence`: 0=start, 1=current, 2=end).
- `pickle` Serialization: Converting Python objects into byte streams (`pickle.dump()`) and restoring them (`pickle.load()`). Security alert: Unpickling untrusted files allows arbitrary code execution via `__reduce__`!
- Zipping & Unzipping: `zipfile.ZipFile()` for creating and extracting compressed ZIP archives.
- Directory Operations: `os.getcwd()`, `os.mkdir()`, `os.listdir()`, `os.path.exists()`, `shutil.copy()`, `shutil.rmtree()`.
graph LR
Object[Python Object: Dict/List] -->|pickle.dump| ByteStream[Binary File .pkl on Disk]
ByteStream -->|pickle.load| RestoredObject[Restored In-Memory Python Object]
FilePointer[File Pointer Offset] -->|seek 0, 0| Start[Beginning of File Byte 0]
FilePointer -->|tell| Position[Return Current Byte Index]
import pickle
import os
import zipfile
# Serialization with Pickle
data = {"user_id": 101, "scores": [95, 88, 92]}
with open("user_data.pkl", "wb") as f:
pickle.dump(data, f)
# Random File Pointer Inspection with seek() and tell()
with open("user_data.pkl", "rb") as f:
print("Initial Pointer:", f.tell())
content = f.read(10)
print("Pointer after 10 bytes:", f.tell())
f.seek(0) # Reset pointer back to start
restored = pickle.load(f)
print("Restored Pickle Object:", restored)
5-Marks Exam Scoring Points
- seek(0) resets the file pointer back to the beginning of a file.
- pickle serializes arbitrary complex Python objects directly to binary files.
- zipfile module extracts and compresses ZIP archive files programmatically.
✍️ Chapter 7 Reference Exercises & Review Problems
with open("data.txt", "r+") as f: # r+ mode for read and write
content = f.read()
word_count = len(content.split())
# Reset pointer back to beginning to inspect
f.seek(0)
first_10_chars = f.read(10)
# Move pointer to end of file to append word count
f.seek(0, 2) # 2 = Seek relative to end of file
f.write(f"\nTotal Word Count: {word_count}\n")
print(f"Word count ({word_count}) written to file successfully.")
- **Purpose:** `pickle` serializes Python objects (converting in-memory data structures into a byte stream) so they can be saved to disk or transmitted across a network and later deserialized back into active memory.
- **Security Risk:** **Unpickling untrusted files is dangerous!** The `pickle` deserialization engine can execute arbitrary Python code (via the `__reduce__` method). Loading a malicious `.pkl` file from an untrusted source can execute arbitrary shell commands on your system!