← Lesson
BitWithBite
Python · Quick Reference

Lesson 13 — File Handling Cheat Sheet

Python
In one line: Python uses open(filename, mode) to open a file. Always use the with statement (context manager) — it guarantees the file is properly closed even if an error occurs. Without wit...

Key Ideas

1Opening Files — The with Statement. Python uses open(filename, mode) to open a file. Always use the with statement (context manager) — it guarantees the file is properly closed even if an error occurs. W...
2CSV Files. CSV (Comma-Separated Values) is the most common format for tabular data — spreadsheets, database exports, data science datasets. Python's built-in csv module handles a...
3JSON Files. JSON (JavaScript Object Notation) is the universal format for web APIs, configuration files, and data exchange. Python's json module converts between Python dicts/list...
4pathlib — Modern Path Handling. Python 3.6+ includes pathlib, the modern object-oriented way to work with file system paths. It's far better than string concatenation for paths — it works identically...

Code Examples

# ── WRITING a file ─────────────────────────── with open("notes.txt", "w", encoding="utf-8") as f: f.write("Line 1: Python is awesome!\n") f.write("Line 2: File handling is easy.\n") f.write("Line 3: Always use 'with'.\n") # File is automatical...
import csv # ── WRITING a CSV ───────────────────────────── students = [ ["Name", "Age", "GPA", "City"], # header row ["Ali", 20, 3.85, "Lahore"], ["Sara", 22, 3.92, "Karachi"], ["Fatima", 21, 3.75, "Islamabad"], ] ...
import json data = { "app" : "BitWithBite", "version": "2.0", "students": [ {"name": "Ali", "gpa": 3.85}, {"name": "Sara", "gpa": 3.92}, ], "active": True } # ── Write to JSON file ──────────────────────── with open...