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 |
|
Automatically calls file.close() upon exiting the block, even if an exception is raised. |
| 2 | Text File Read Return Types |
|
read() reads full content; readline() reads line-by-line; readlines() loads lines into list. |
| 3 | File Pointer Positioning Methods |
|
In text files, whence is restricted to 0 (or offset 0 for 1 and 2); binary files allow arbitrary offsets. |
| 4 | Binary Pickling Serialization |
|
Serializes in-memory Python structures (lists, dicts) into persistent binary bytecode format. |
| 5 | Binary Unpickling Deserialization Loop |
|
Standard pattern for sequentially reading multiple records from a binary file until End-of-File. |
| 6 | CSV Writer Initialization Formula |
|
Default delimiter is comma; handles escaping and quote wrapping automatically. |
| 7 | CSV Row and Matrix Writing |
|
writerow writes one record; writerows writes a complete 2D matrix of records. |
| 8 | CSV File Opening Newline Protocol |
|
Specifying newline='' prevents the CSV writer on Windows from injecting unwanted blank empty lines. |
| 9 | Word Count Algorithm in Text File |
|
Splits lines on whitespace, counting total words accurately. |
| 10 | Character / Vowel Count Algorithm |
|
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.
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.
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()`.