Lab 08: File I/O

🎯 Objective

Read and write text files, work with CSV data, use context managers safely, and handle file system operations — skills essential for data processing, logging, and configuration.

📚 Background

File I/O (Input/Output) is how programs persist data beyond their execution. Python's open() function handles text and binary files. The with statement (context manager) ensures files are always properly closed — even if an error occurs. The csv module handles the ubiquitous CSV format. The pathlib module (Python 3.4+) provides an object-oriented approach to file paths.

⏱️ Estimated Time

30 minutes

📋 Prerequisites

  • Lab 7: Functions & Scope

🛠️ Tools Used

  • Python 3.12

🔬 Lab Instructions

Step 1: Writing Files

📸 Verified Output:

💡 Always use with open(...) as f: — it's a context manager that automatically calls f.close() when the block exits, even if an exception is raised. Never rely on the garbage collector to close files.

Step 2: Reading Files

📸 Verified Output:

Step 3: Working with CSV Files

📸 Verified Output:

Step 4: JSON Files

📸 Verified Output:

Step 5: pathlib — Modern Path Handling

📸 Verified Output:

Step 6: Error Handling with Files

📸 Verified Output:

Step 7: Log File Pattern

📸 Verified Output:

Step 8: Processing a Data File

📸 Verified Output:

✅ Verification

Expected output:

🚨 Common Mistakes

  1. Not using with: f = open(...) without with — if an exception occurs, the file is never closed, causing resource leaks.

  2. Wrong mode: open(f, "w") destroys existing content — use "a" to append.

  3. Missing newline="" in CSV writer: Causes extra blank lines on Windows.

  4. Reading large files with .read(): Loads entire file into memory — use line-by-line iteration for big files.

  5. Hardcoded paths: "/home/user/file.txt" breaks on other machines — use pathlib with relative paths.

📝 Summary

  • with open(path, mode) as f: — always use context manager for automatic close

  • Modes: "r" read, "w" write (overwrites!), "a" append, "rb" binary read

  • csv.DictReader / csv.writer — handle CSV properly (quote escaping, headers)

  • json.dump() / json.load() — serialize Python dicts to/from JSON files

  • pathlib.Path — object-oriented paths; Path("/dir") / "file.txt" for joining

  • For large files: iterate line by line, don't f.read() the whole thing

🔗 Further Reading

Last updated