Circle of Learning Logo CIRCLE OF LEARNING Excellence in Education
CBSE Class 12 · Computer Science Chapter 4 Session 2026-27

File Handling - Text, Binary & CSV Files Formulas & Cheat Sheet

Complete chapter-wise reference, step-by-step formula explanations, structured table, and board exam trap warnings.

Core Concepts & Theoretical Foundations

  • File Types: 1) Text Files (.txt): Human-readable characters encoded in ASCII/UTF-8; each line terminated by End-of-Line (EOL, `\n`). 2) Binary Files (.dat): Stores raw bytes directly without translation (exact memory dump); requires `pickle` module. 3) CSV Files (.csv): Comma-Separated Values storing tabular data in plain text; requires `csv` module.
  • File Modes: Read (`'r'`), Write (`'w'`, overwrites), Append (`'a'`), Read & Write (`'r+'`, `'w+'`, `'a+'`). Binary modes append `'b'` (`'rb'`, `'wb'`, `'ab'`).
  • Text File Reading Methods: `read()` (reads entire file as single string), `readline()` (reads single line as string including newline), `readlines()` (reads all lines as a list of strings).
  • Pickle Module (Binary): `pickle.dump(object, file_handle)` serializes object to binary file; `pickle.load(file_handle)` deserializes binary stream back into Python object. Must handle `EOFError` when reading in a loop.
  • CSV Module: `csv.reader(file_handle)` returns an iterable row reader; `csv.writer(file_handle)` creates writer; `writer.writerow(list)` writes single row; `writer.writerows(list_of_lists)` writes multiple rows. Use `newline=''` when opening CSV files.

Chapter Formulas & Equations (10 entries)

# Topic / Formula Name Mathematical Form & Equation Conditions, Meaning & Board Tips
1 Context Manager Safe File Opening Formula
with open(F,M) as f:(Auto closes upon block exit)\text{with open}(F, M) \text{ as } f: \quad (\text{Auto closes upon block exit})

Automatically calls file.close() upon exiting the block, even if an exception is raised.

2 Text File Read Return Types
read()  ⟹  str;readline()  ⟹  str;readlines()  ⟹  [str1,str2,… ]\text{read}() \implies \text{str}; \quad \text{readline}() \implies \text{str}; \quad \text{readlines}() \implies [\text{str}_1, \text{str}_2, \dots]

read() reads full content; readline() reads line-by-line; readlines() loads lines into list.

3 File Pointer Positioning Methods
seek(offset,whence):whence∈{0:start,1:current,2:end}\text{seek}(\text{offset}, \text{whence}): \quad \text{whence} \in \{0: \text{start}, 1: \text{current}, 2: \text{end}\}

In text files, whence is restricted to 0 (or offset 0 for 1 and 2); binary files allow arbitrary offsets.

4 Binary Pickling Serialization
pickle.dump(O,fbin)\text{pickle.dump}(O, f_{\text{bin}})

Serializes in-memory Python structures (lists, dicts) into persistent binary bytecode format.

5 Binary Unpickling Deserialization Loop
while True:try load(f)except EOFError:break\text{while True}: \text{try } \text{load}(f) \quad \text{except EOFError}: \text{break}

Standard pattern for sequentially reading multiple records from a binary file until End-of-File.

6 CSV Writer Initialization Formula
W=csv.writer(f,delimiter)W = \text{csv.writer}(f, \text{delimiter})

Default delimiter is comma; handles escaping and quote wrapping automatically.

7 CSV Row and Matrix Writing
writerow([c1,c2,… ]);writerows([[r11,r12],[r21,r22]])\text{writerow}([c_1, c_2, \dots]); \quad \text{writerows}([[r_{11}, r_{12}], [r_{21}, r_{22}]])

writerow writes one record; writerows writes a complete 2D matrix of records.

8 CSV File Opening Newline Protocol
open(F,′w′,newline=′′)\text{open}(F, 'w', \text{newline}='')

Specifying newline='' prevents the CSV writer on Windows from injecting unwanted blank empty lines.

9 Word Count Algorithm in Text File
Word Count=∑i=1n∣linei.split()∣\text{Word Count} = \sum_{i=1}^n |\text{line}_i.\text{split}()|

Splits lines on whitespace, counting total words accurately.

10 Character / Vowel Count Algorithm
Vowels=∑[c∈{a,e,i,o,u}]\text{Vowels} = \sum [c \in \{a, e, i, o, u\}]

Standard board exam text processing query.

Step-by-Step Worked Board Exam Examples

Example 1: Write a Python function `count_lines_starting_with_T(filename)` that reads a text file and counts how many lines begin with the letter 'T' or 't'.

1. Open file using `with open(filename, 'r') as f:`.

2. Initialize count = 0.

3. Loop through lines: `for line in f:`.

4. Strip leading spaces using `line.strip()` and check if it starts with 'T' or 't':

`if line.strip().startswith(('T', 't')):` -> increment count.

5. Return count.

Ans: ```python def count_lines_starting_with_T(filename): count = 0 with open(filename, 'r') as f: for line in f: stripped = line.strip() if stripped and stripped[0] in ('T', 't'): count += 1 return count ```

Example 2: Write a function in Python to read a binary file `students.dat` containing student records stored as dictionaries `{'roll': int, 'name': str, 'marks': float}` and display the records of students scoring >= 90 marks.

1. Import pickle module.

2. Open file in `'rb'` mode inside a try-except block.

3. Use `while True:` loop calling `rec = pickle.load(f)`.

4. Check if `rec['marks'] >= 90` -> print record.

5. Catch `EOFError` when end of file is reached, and catch `FileNotFoundError` if file missing.

Ans: ```python import pickle def display_toppers(): try: with open('students.dat', 'rb') as f: print('--- Students Scoring >= 90 Marks ---') while True: try: rec = pickle.load(f) if rec['marks'] >= 90: print(f"Roll: {rec['roll']}, Name: {rec['name']}, Marks: {rec['marks']}") except EOFError: break except FileNotFoundError: print('Error: students.dat not found!') ```

Common Mistakes to Avoid in Exam

  • Forgetting `newline=''` when creating CSV files: Omitting `newline=''` causes Python on Windows to insert an extra blank line between every row.
  • Using `read()` on massive files: `read()` loads the entire file into RAM at once; for large files, iterate line by line `for line in f:` to conserve memory.
  • Attempting to read text files in binary mode without decoding: Reading in `'rb'` returns `bytes` objects (e.g. `b'Hello'`), causing string operations to fail.
  • Forgetting to handle `EOFError` in binary file unpickling: `pickle.load()` does not return an empty string at EOF; it raises `EOFError` which must be caught to cleanly terminate the loop.

Target Practice Questions

Q1. What will `f.read(5)` return from a text file containing 'Computer Science'?

Correct Answer: It will return the first 5 characters: `'Compu'`.

Q2. Which module must be imported to work with binary files in Python?

Correct Answer: The `pickle` module.

Q3. State the default file opening mode if no mode parameter is passed to `open('notes.txt')`.

Correct Answer: The default mode is `'r'` (read mode for text files).

Frequently Asked Questions

Q. What is the difference between `w` and `a` file modes?

Mode `'w'` (write) creates a new file or completely truncates (erases) existing contents before writing. Mode `'a'` (append) opens the file and positions the file pointer at the very end, appending new data without overwriting existing content.

Q. What is the function of `f.tell()` and `f.seek()` in file handling?

`f.tell()` returns the current byte position of the file pointer. `f.seek(offset, whence)` moves the file pointer to a new position relative to reference point whence (0: beginning, 1: current position, 2: end of file).

Q. What is serialization / pickling in Python?

Serialization (or pickling) is the process whereby a Python object hierarchy (such as lists or dictionaries) is converted into a byte stream. Deserialization (unpickling) reconstructs the object from the byte stream.

Q. Why is `with` statement preferred over regular `open()` and `close()`?

Because `with` statement utilizes context management protocol (`__enter__` and `__exit__`), guaranteeing that the file is automatically closed when execution leaves the block, even if runtime exceptions or returns occur.

Q. What delimiter is used by default in CSV files, and can it be changed?

The default delimiter is a comma (`,`). It can be changed to any character (such as tab `\t`, pipe `|`, or semicolon `;`) by passing `delimiter='\t'` to `csv.reader()` or `csv.writer()`.

← View All 11 Chapters in Class 12 Computer Science Formula Book