Reference Manual • Chapter 7

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:

🚪 Layman Analogy: Leaving a Room vs Automatic Self-Closing Door

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:

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]
                    
Architecture Specification 7.1: Object Serialization & File Pointer Mechanics
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

Exercise 7.1: Write a Python program that opens a text file `data.txt`, counts the number of words, resets the file pointer to the beginning using `seek()`, and writes the word count at the end of the file.
Step-by-Step Reference Solution:
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.")
Exercise 7.2: What is the purpose of `pickle` in Python? Highlight security risks when unpickling untrusted files.
Step-by-Step Reference Solution:
- **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!