File I/O, JSON and CSV
What is it?
File Input/Output (I/O) is the subsystem through which a Python program exchanges data with persistent non-volatile storage (SSDs, hard drives, network filesystems):
- Text & Binary Modes: Direct stream handling via
open(filename, mode, encoding). - Context Managers (
with open(...)): Scoped execution blocks that guarantee files are cleanly flushed and closed, preventing operating system resource leaks. pathlib.Path: Modern object-oriented filesystem manipulation replacing brittle string concatenation.- Serialization Formats:
- CSV (
csvmodule): Universal standard for raw tabular datasets. - JSON (
jsonmodule): Structured, human-readable format for hyperparameter configurations, token vocabularies, and model metadata. - Binary Formats (
pickle,joblib, Safetensors): Fast serialization of learned weights and compiled pipelines.
- CSV (
File Mode Matrix
Why we need it
In production machine learning:
- Crash-Resistant Experiment Logging: If an error crashes a 12-hour training script at epoch 98, unclosed file buffers can lose all logged metric points. Context managers guarantee logs are flushed to disk.
- Cross-Platform Path Portability: Hardcoding forward slashes (
/) or backslashes (\) causes scripts to crash when moved between Windows workstations and Linux GPU cloud clusters.pathlib.Pathprovides universal portability. - Hyperparameter Reproducibility: Serializing model configurations (
learning_rate,batch_size,optimizer) to.jsonfiles alongside model weights allows exact reproduction of historical benchmark experiments. - Model Checkpointing Security: Machine learning engineers must understand the serious security vulnerabilities of unpickling untrusted model files downloaded from the web.
Explained in detail
1. The Context Manager: How with Prevents Resource Leaks
Opening a file requests a file descriptor from the operating system kernel. Operating systems strictly cap the maximum number of simultaneous open file descriptors (often 1024 by default). If you open files in a loop without closing them, the process crashes with OSError: [Errno 24] Too many open files.
The with statement utilizes the Context Manager Protocol:
- It calls the object's
__enter__()method to acquire the resource. - It executes the enclosed block.
- It calls
__exit__()automatically β even if an unhandled exception or crash occurs!
# Safe, leak-proof text writing:
with open("training_log.txt", "w", encoding="utf-8") as f:
f.write("epoch,loss,accuracy\n")
f.write("1,0.521,0.854\n")
f.write("2,0.384,0.912\n")
# Reading lines lazily (streams file line-by-line without loading entire file to RAM):
with open("training_log.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())Think of opening a file as turning on a water tap in a laboratory sink. Opening a file without with requires you to remember to manually turn off the handle (f.close()). If you slip or get distracted by an error, the sink overflows and floods the building (OS descriptor exhaustion). A with block is a spring-loaded foot pedal: the water flows only while your foot is pressed down, and shuts off instantly the moment you step away.
2. Building a Custom Context Manager for ML Timing
You can write your own context manager by implementing __enter__ and __exit__:
import time
class EpochTimer:
"""Measures and logs elapsed wall-clock time for a training phase."""
def __init__(self, phase_name: str):
self.phase_name = phase_name
self.start_time = None
def __enter__(self):
self.start_time = time.perf_counter()
print(f"[{self.phase_name}] Started...")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
elapsed = time.perf_counter() - self.start_time
print(f"[{self.phase_name}] Finished in {elapsed:.3f} seconds.")
# Returning False propagates exceptions; returning True suppresses them
return False
# Usage:
with EpochTimer("Model Validation"):
time.sleep(0.1) # Simulate computing validation metrics3. Modern Filesystem Operations with pathlib.Path
Avoid legacy os.path.join and raw string manipulations. The pathlib module represents filesystem paths as first-class objects:
from pathlib import Path
# 1. Path composition using the division operator '/'
project_dir = Path("./experiments")
checkpoint_dir = project_dir / "run_01" / "checkpoints"
# 2. Directory creation (creates parent directories safely, ignores if existing)
checkpoint_dir.mkdir(parents=True, exist_ok=True)
# 3. Path inspection
model_file = checkpoint_dir / "best_model.pt"
print("File name:", model_file.name) # "best_model.pt"
print("File stem:", model_file.stem) # "best_model"
print("Extension:", model_file.suffix) # ".pt"
print("Exists? :", model_file.exists()) # False
# 4. Globbing: recursively search for all CSV files in a dataset folder
data_dir = Path("./data")
for csv_path in data_dir.glob("**/*.csv"):
print("Discovered dataset:", csv_path)4. JSON Serialization & Custom Encoders for ML
JSON (JavaScript Object Notation) represents strings, numbers, booleans, lists, and key-value maps:
json.dump(obj, file): Serializes object to a file.json.dumps(obj): Serializes object to an in-memory string.json.load(file): Deserializes file to Python object.json.loads(string): Deserializes string to Python object.
import json
experiment_metadata = {
"model_name": "ResNet18",
"hyperparameters": {
"learning_rate": 0.001,
"batch_size": 64,
"optimizer": "AdamW",
},
"metrics": {
"best_val_accuracy": 0.942,
"converged": True,
}
}
# Save formatted JSON with indentation
config_path = Path("experiment_config.json")
with open(config_path, "w", encoding="utf-8") as f:
json.dump(experiment_metadata, f, indent=2, sort_keys=True)The NumPy Type Serialization Error: Python's standard json module cannot serialize NumPy numbers (np.float32, np.int64, or np.ndarray), raising TypeError: Object of type float32 is not JSON serializable. Always convert NumPy scalars using float(val) or implement a custom json.JSONEncoder!
class MLJSONEncoder(json.JSONEncoder):
"""Handles NumPy and Path objects during JSON serialization."""
def default(self, obj):
# Convert Path objects to strings
if isinstance(obj, Path):
return str(obj)
# Convert objects with tolist() (like NumPy arrays) to standard Python lists
if hasattr(obj, "tolist"):
return obj.tolist()
return super().default(obj)5. CSV Parsing and Tabular Datasets
Python's csv module parses comma-separated or tab-separated records without requiring pandas:
import csv
# 1. Writing tabular datasets with DictWriter
training_samples = [
{"sample_id": 101, "feature_x": 0.85, "label": "spam"},
{"sample_id": 102, "feature_x": 0.12, "label": "ham"},
]
csv_file = Path("samples.csv")
with open(csv_file, "w", newline="", encoding="utf-8") as f:
fieldnames = ["sample_id", "feature_x", "label"]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(training_samples)
# 2. Reading tabular datasets with DictReader
with open(csv_file, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"Sample {row['sample_id']} has label: {row['label']}")6. Binary Serialization & The Security Warning of pickle
For serializing complex Python objects (such as trained Scikit-learn pipelines), the standard library provides pickle, and high-performance libraries provide joblib:
import pickle
trained_weights = {"w1": [0.2, 0.4], "b1": 0.05}
# Serializing to binary:
with open("weights.pkl", "wb") as f:
pickle.dump(trained_weights, f)
# Deserializing from binary:
with open("weights.pkl", "rb") as f:
loaded_weights = pickle.load(f)CRITICAL SECURITY WARNING: Never Unpickle Untrusted Files!
Python's pickle format is executable bytecode. Deserializing a malicious .pkl or .pt file downloaded from an untrusted source can execute arbitrary shell commands on your operating system! For sharing public weights, always prefer safe formats like Safetensors or ONNX.
Quiz
π§©
Ready to test yourself?
4 questions Β· explanations shown after
Teach & Solidify
Teach This: File I/O, JSON and CSV
Core Intuition
Always use `with open(...)` with explicit UTF-8 encoding; manipulate filesystem paths portably with pathlib.Path; use JSON for configs and beware of pickle security risks.
Key Concepts to Explain
- 1Use `with open(..., encoding="utf-8")` to eliminate file descriptor leaks and cross-platform encoding bugs.
- 2Use `pathlib.Path` instead of string concatenation to guarantee cross-platform compatibility between Windows and Linux.
- 3Serialize model configurations into human-readable `.json` files to preserve exact experiment provenance.
- 4Never use `pickle.load()` on untrusted model weight files from unknown internet sources β prefer Safetensors.
β οΈ What Most Students Get Confused About
Forgetting `newline=''` when creating `csv.writer` on Windows: Windows line terminators (`\r\n`) will cause empty blank rows between data lines!
Explain File I/O, JSON and CSV in your own words
Imagine you are explaining this idea to a friend or classmate with no math background. Writing it out forces your brain to bridge gaps in your intuition.
Resources & GitHub
Resources & Study Materials
Deepen your understanding with author-prepared study notes, derivation proofs, and curated educational lectures.
Official guide to modern filesystem operations, path resolution, and globbing.
Security and performance guide on moving away from pickle to memory-mapped, safe tensor serialization.
Interactive Jupyter notebook with custom context managers and JSON serialization recipes.
Mastered this concept?
Tick this box when you feel confident explaining it.
Topic Resources
Python_File_IO_and_CSV_Processing.py
Python Script2.9 KB Β· Modified Latest
Was this clear?