Python File Handling: Reading, Writing, CSV, JSON, Context Managers, pathlib, Encoding, Large Files, and Every File Pattern Data Engineers Use
Complete Python file handling guide. Opening and closing files (the dangerous way vs context managers with hotel analogy). All file modes explained (r, w, a, x, r+, rb with decision table). Reading files (read, readline, readlines, iterating line by line for large files with photocopy analogy). Writing files (write, writelines, append, print to file). pathlib for modern file paths (why over os.path with GPS analogy, common operations, building paths, glob, rglob, checking existence, creating directories). CSV files (csv.reader vs DictReader with spreadsheet analogy, csv.writer vs DictWriter, handling commas and quotes and encoding). JSON files (load vs loads, dump vs dumps, memory trick for s=string, pretty printing, nested JSON safe access, custom serializer for datetime and Decimal). Working with large files (line-by-line, chunked reading, counting lines). Encoding and Unicode (UTF-8, latin-1, BOM from Excel with utf-8-sig, chardet detection). File operations (copy, move, delete with shutil and pathlib). Data engineering patterns (config file reader, process all CSVs in directory, safe temp file writer, file-based logging). 7 common mistakes and 6 interview Q&As.