Ch 2 covers file handling — reading from and writing to files for persistent data storage. Learn text files, binary files, CSV files, file modes, and the pickle module for object serialisation.
Open: f = open("data.txt", "r"). Modes: "r" (read — default), "w" (write — overwrites), "a" (append), "r+" (read+write). Read: f.read() — entire file, f.read(n) — n characters, f.readline() — one line, f.readlines() — list of all lines. Write: f.write("text"), f.writelines(list). Close: f.close() (always close!). Better: with open("data.txt") as f: — automatically closes, even if error occurs. seek(offset, from) and tell(): move and check file pointer position.
Binary files: store data in raw binary format. Modes: "rb", "wb", "ab". Pickle module: serialises Python objects to binary. import pickle; pickle.dump(object, file) — write; pickle.load(file) — read. Useful for saving lists, dictionaries, class objects. CSV files: Comma-Separated Values — tabular data as text. import csv; reader = csv.reader(file); for row in reader: — each row is a list. writer = csv.writer(file); writer.writerow([a, b, c]); writer.writerows(list_of_lists). CSV is interoperable with Excel, databases, data science tools.
Download: https://ncert.nic.in/textbook/pdf/lecs102.pdf | Complete Book: https://ncert.nic.in/textbook/pdf/lecs1ps.zip
Text mode ("r", "w", "a"): reads/writes strings, handles newline conversion (\n ↔ OS-specific line ending), default encoding (UTF-8). Binary mode ("rb", "wb", "ab"): reads/writes bytes objects, no encoding/newline conversion. Use text mode for human-readable files (txt, csv, html, json). Use binary mode for non-text data (images, audio, pickle files, executables) or when you need exact byte-level control. Trying to read a binary file in text mode gives garbled output or errors.
Book a Trial + Diagnostic session. Get a personalized Learning Path with clear milestones, tutor match, and a plan recommendation — all within 24 hours.
Book Trial + Diagnostic →