Complete Summary and Solutions for File Handling in Python – NCERT Class XII Computer Science, Chapter 2 – Text Files, Binary Files, Opening, Closing, Reading, Writing, Pickle Module, Questions, Answers
Detailed summary and explanation of Chapter 2 'File Handling in Python' from the Computer Science textbook for Class XII, covering types of files (text and binary), file opening and closing modes, reading and writing operations, file pointer functions (seek and tell), pickling and unpickling with the pickle module, and practical examples—along with all NCERT questions, answers, and exercises.
File Handling in Python - Class 12 Computer Science Chapter 2 Ultimate Study Guide 2025
File Handling in Python
Chapter 2: Computer Science - Ultimate Study Guide | NCERT Class 12 Notes, Questions, Code Examples & Quiz 2025
Full Chapter Summary & Detailed Notes - File Handling in Python Class 12 NCERT
Overview & Key Concepts
Chapter Goal: Understand files for permanent data storage; types (text/binary), operations (open/close/read/write/offsets), pickle for objects. Exam Focus: Open modes Table 2.1, Programs 2-1 to 2-8, Fig 2.1; 2025 Updates: Emphasis on binary handling in data science. Fun Fact: Robin Milner quote on program understanding ties to file persistence. Core Idea: From volatile vars to reusable files; real-world: Employee records. Expanded: All subtopics point-wise with evidence (e.g., Program 2-1 output), examples (e.g., seek(10,0)), debates (e.g., text vs binary efficiency).
Wider Scope: From secondary storage to serialization; sources: Programs (2-1 to 2-8), tables (2.1), figures (2.1). Interlinks: To exceptions Ch1 for file errors.
Expanded Content: Include modern aspects like CSV/JSON handling, pathlib module; point-wise for recall; add 2025 relevance like async file I/O.
Introduction & Types of Files
Files Overview: Named secondary storage for reuse; vars temporary, files permanent (e.g., employee data). Ex: .py scripts as files.
Text Files: Human-readable chars (ASCII/UNICODE); EOL \n; separated by space/,/\t. Ex: .txt, .py, .csv; Activity 2.1: .txt bytes vs .docx KBs (metadata).
dump(): pickle.dump(obj, file); Ex: Program 2-6: List to mybinary.dat.
load(): obj = pickle.load(file); Ex: Program 2-7: Loads list [1, 'Geetika', ...].
Program 2-8: Employee records (list) append/load; try-except EOFError; output: Records + size 216.
Expanded: Evidence: Page 32-35; debates: JSON vs pickle (security).
Summary & Exercise
Key Takeaways: Files for persistence; text/binary diff; io methods; pickle for objects. Close always; with safer.
Exercise Tease: Diff text/binary; modes; programs for read/write/pickle.
Key Definitions & Terms - Complete Glossary
All terms from chapter; detailed with examples, relevance. Expanded: 30+ terms grouped by subtopic; added advanced like "Serialization", "Buffer" for depth/easy flashcards.
Text File
Human-readable chars sequence. Ex: .txt with \n. Relevance: Easy edit.
open() return obj. Ex: myobj. Relevance: Data transfer.
Access Mode
r/w/a/b/+ for ops. Ex: "r+" read/write. Relevance: Offset control.
EOL
End of line char. Ex: \n. Relevance: Line separation.
Buffer
Temp memory for writes. Ex: Flush on close. Relevance: Efficiency.
Offset
Byte position. Ex: tell()=0 begin. Relevance: Random access.
Pickling
Object to byte stream. Ex: dump(list). Relevance: Persistence.
Unpickling
Bytes to object. Ex: load(). Relevance: Retrieval.
write()
String to file. Ex: write("Hi\n")=3. Relevance: Single output.
writelines()
List/tuple to file. Ex: writelines(["A\n","B\n"]). Relevance: Multiple.
read()
Bytes from file. Ex: read(5)="Hello". Relevance: Partial/full.
readline()
One line. Ex: readline()="Line\n". Relevance: Line-by-line.
readlines()
List of lines. Ex: ['Line1\n','Line2']. Relevance: All lines.
tell()
Current pos. Ex: tell()=10. Relevance: Position check.
seek()
Move pos. Ex: seek(0,0) begin. Relevance: Random read.
with Clause
Auto close. Ex: with open() as f:. Relevance: Safe handling.
Serialization
Obj to bytes. Ex: Pickle dump. Relevance: Storage.
Deserialization
Bytes to obj. Ex: Pickle load. Relevance: Restore.
EOF
End of file. Ex: readline()="" . Relevance: Loop stop.
Flush
Buffer to disk. Ex: f.flush(). Relevance: Force write.
Tip: Group by type/op; examples for recall. Depth: Debates (e.g., pickle security). Errors: Forget close. Historical: Python 3.12 paths. Interlinks: To Ch1 exceptions. Advanced: Custom serializers. Real-Life: Database dumps. Graphs: Modes table. Coherent: Evidence → Interpretation. For easy learning: Flashcard per term with code.
60+ Questions & Answers - NCERT Based (Class 12) - From Exercises & Variations
Based on chapter + expansions. Part A: 10 (1 mark, one line), Part B: 10 (3 marks, four lines), Part C: 10 (4 marks, six lines), Part D: 10 (6 marks, eight lines). Answers point-wise in black text. Include code where apt.
Part A: 1 Mark Questions (10 Qs - Short)
1. What is a file?
1 Mark Answer:
Named secondary storage location.
2. Diff text vs binary file?
1 Mark Answer:
Readable chars vs byte stream.
3. Default EOL in Python?
1 Mark Answer:
\n.
4. open() returns?
1 Mark Answer:
File object/handle.
5. Purpose of close()?
1 Mark Answer:
Free resources, flush buffer.
6. with clause benefit?
1 Mark Answer:
Auto close.
7. write() returns?
1 Mark Answer:
Chars written.
8. readline() at EOF?
1 Mark Answer:
Empty string.
9. tell() returns?
1 Mark Answer:
Byte position.
10. Pickling is?
1 Mark Answer:
Serialization.
Part B: 3 Marks Questions (10 Qs - Medium, Exactly 4 Lines Each)
1. Diff text/binary files.
3 Marks Answer:
Text: Readable, ASCII, \n EOL.
Binary: Bytes, non-readable, app-specific.
Ex: .txt vs .jpg.
Text easy, binary efficient.
2. List 3 open modes with offsets.
3 Marks Answer:
r: Read, begin.
w: Write/overwrite, begin.
a: Append, end.
Table 2.1.
3. Explain close() need.
3 Marks Answer:
Frees memory, flushes data.
Auto on reassign/with.
Ex: Unsaved → lost.
Best practice.
4. Diff write() vs writelines().
3 Marks Answer:
write: Single str, returns count.
writelines: Iterable strs, no return.
Ex: write("Hi\n"); writelines(["A\n","B\n"]).
Activity 2.3.
5. read() vs readline().
3 Marks Answer:
read: Bytes/full file.
readline: One line to \n.
Ex: read(10)="Hello ever".
Loop for all.
6. tell() and seek() syntax.
3 Marks Answer:
tell: Current byte.
seek(offset, ref=0).
Ex: seek(10,0) begin+10.
Program 2-2.
7. with vs manual close.
3 Marks Answer:
with: Auto close, exception-safe.
Manual: Explicit close().
Ex: with open("f.txt","r") as obj: read.
Simpler syntax.
8. readlines() output.
3 Marks Answer:
List of lines + \n.
Ex: ['Hello\n','World'].
split() words; splitlines() clean.
Page 27.
9. Pickle dump/load.
3 Marks Answer:
dump: Obj to binary wb.
load: Binary rb to obj.
Ex: dump([1,2],f).
Serialization.
10. Buffer role.
3 Marks Answer:
Temp write storage.
Close/flush to disk.
Ex: write() to buffer.
Efficiency.
Part C: 4 Marks Questions (10 Qs - Medium-Long, Exactly 6 Lines Each)
1. Explain text file structure.
4 Marks Answer:
Char sequence, ASCII bytes.
EOL \n terminates lines.
Separators: space/,/\t.
Ex: 65='A'; editor translates.
Activity 2.1 size diff.
Human-readable.
2. Describe 4 open modes.
4 Marks Answer:
r: Read, begin (error if no file).
w: Write, begin (overwrite/create).
a: Append, end (create).
r+: Read/write, begin.
Table 2.1 offsets.
b for binary.
3. How seek/tell work? Code.
4 Marks Answer:
tell: Pos int.
seek: Move bytes from ref.
Ex: seek(0,0) begin.
Program 2-2: seek(10), read partial.
Random access.
Bytes-based.
f.seek(10, 0)
print(f.tell()) # 10
4. Writing methods with ex.
4 Marks Answer:
write: Str, \n manual.
writelines: List, no \n auto.
Ex: write(str(58))=2.
Fig 2.1 multiline.
Buffer flush.
Num to str.
5. Reading process.
4 Marks Answer:
read: All/partial.
readline: Line loop EOF empty.
readlines: List.
Ex: Program 2-1 loop print.
split for words.
r/r+/w+/a+ modes.
6. Creating/traversing code.
4 Marks Answer:
w: Create/overwrite.
a: Append.
Program 2-3: Loop write.
Program 2-4: readline loop.
w+: seek(0) read.
Program 2-5 output.
7. Pickle overview.
4 Marks Answer:
Serialize obj binary.
dump wb, load rb.
Ex: Program 2-6 list dump.
Program 2-7 load print.
EOFError try-except.
Object persistence.
8. Diff open modes w/a.
4 Marks Answer:
w: Overwrite begin.
a: Append end.
New file: Same create.
Ex: w erases, a adds.
Offsets diff.
Think reflect.
9. Why close files?
4 Marks Answer:
Flush unsaved data.
Free resources.
No error if forget (auto sometimes).
Ex: Buffer to disk.
with prevents forget.
Best practice.
10. Buffer in writing.
4 Marks Answer:
Temp hold writes.
close/flush to permanent.
Ex: write() buffer, close disk.
Efficient batch.
flush() force.
Page 24.
Part D: 6 Marks Questions (10 Qs - Long, Exactly 8 Lines Each)
1. Justify text files for data reuse.
6 Marks Answer:
Vars temporary; files permanent.
Avoid re-entry (employees/sales).
Text: Readable, ASCII seq.
Ex: .py/.csv.
Activity 2.1: Bytes small.
No metadata bloat.
Evidence: Intro page 19.
Reusability key.
2. When used: r/w/a/rb/wb/ab modes. Ex.
6 Marks Answer:
r: Read exist, begin.
Ex: open("f.txt","r").
w: Write/overwrite, begin.
Ex: Create new.
a: Append end.
Ex: Log add.
rb: Binary read.
wb/ab: Binary write/append.
3. Write program: User input to file, read display.
6 Marks Answer:
Like Program 2-1.
open w, write input.
close, open r, loop print.
Ex: Code below.
Output: Echo.
Traversing.
Robust with with.
Ch2 ex 8 var.
with open("test.txt","w") as f:
f.write(input("Enter: "))
with open("test.txt","r") as f:
for line in f: print(line)
4. Use seek in random access.
6 Marks Answer:
After write, seek(0) read.
Ex: Program 2-5 tell/seek.
ref 0/1/2.
Output: Position 67 → 0, read.
Bytes count.
Text/binary same.
Program 2-2 partial.
Efficient large files.
5. Define: File Handle, Serialization, Buffer.
6 Marks Answer:
Handle: open return for ops.
Ex: Transfer data.
Serialization: Obj to bytes (pickling).
Ex: dump list.
Buffer: Temp write hold.
Ex: Flush on close.
Page 21/32/24.
Persistence tools.
6. Explain reading with code.
6 Marks Answer:
Methods: read/readline/readlines.
Loop readline EOF.
Ex: Program 2-4 display.
splitlines clean.
Output: Lines printed.
r mode.
Activity 2.4 iterator.
Traversing key.
with open("f.txt","r") as f:
lines = f.readlines()
for l in lines: print(l.strip())
7. Pickle employee records code.
6 Marks Answer:
import pickle; ab mode dump lists.
Loop input eno/name/sal.
try load loop except EOF.
Ex: Program 2-8 output records.
Size tell().
Binary .dat.
Ch2 ex 10 var.
Object store.
8. w+ mode read/write code.
6 Marks Answer:
open "w+"; write then seek(0) read.
Ex: Program 2-5 sentences.
Output: Input echo.
Begin pos after write.
Single obj.
vs separate files.
Efficient.
Ch2 ex 7.
f = open("rep.txt","w+")
f.write("Hi\n")
f.seek(0)
print(f.read())
9. Why pickle for objects?
6 Marks Answer:
Vars temp; pickle persists lists/dicts.
Binary dump/load.
Ex: Game state [level,score].
Program 2-8 employees.
try EOF safe.
vs text str convert.
Ch2 ex 9.
De/serialize.
10. File handling in Python vs others.
6 Marks Answer:
io module open modes.
with auto close (like Java try-with).
Pickle unique serialize.
Ex: seek random (C fseek).
Text default, b binary.
2025: Pathlib obj-oriented.
Clean, robust.
Ch2 summary.
Tip: Include code in ans; practice run. Additional 30 Qs: Variations on programs, modes scenarios.
Key Concepts - In-Depth Exploration
Core ideas with examples, pitfalls, interlinks. Expanded: All concepts with steps/examples/pitfalls for easy learning. Depth: Debates, analysis.
Steps: 1. Full path if not cwd. Ex: open("/path/file.txt"). Pitfall: Wrong dir. Interlink: OS module. Depth: Pathlib 2025.
Advanced: JSON pickle alt, async files. Pitfalls: Unclosed leaks. Interlinks: To Ch3 stacks for recursion files. Real: CSV pandas. Depth: 14 concepts details. Examples: Real outputs. Graphs: Modes table. Errors: Mode mismatch. Tips: Steps evidence; compare tables (read vs write).
Code Examples & Programs - From Text with Simple Explanations
Expanded with evidence, analysis; focus on applications. Added variations for practice.
Example 1: Open Modes (Table 2.1)
Simple Explanation: Set ops/pos.
with open("test.txt", "w") as f: # Create/overwrite
f.write("Hello")
with open("test.txt", "a") as f: # Append
f.write(" World")
Step 1: w begin write.
Step 2: a end add.
Step 3: File="Hello World".
Simple Way: Choose mode.
Example 2: write/writelines (Page 24)
Simple Explanation: Output to file.
f = open("myfile.txt", "w")
f.write("Hey I have started\n") # 41 chars
lines = ["Hello\n", "World\n"]
f.writelines(lines)
f.close()
Step 1: Single str write.
Step 2: List multi.
Step 3: Fig 2.1 content.
Simple Way: \n manual.
Example 3: read Methods (Page 25)
Simple Explanation: Input from file.
f = open("myfile.txt", "r")
print(f.read(10)) # 'Hello ever'
print(f.readline()) # 'Hello everyone\n'
print(f.readlines()) # List lines
f.close()
Step 1: Partial/full.
Step 2: Line/list.
Step 3: EOF empty.
Simple Way: Loop readline.
Example 4: Program 2-1 Write/Read (Page 27)
Simple Explanation: User echo.
f = open("testfile.txt", "w")
sentence = input("Enter: ")
f.write(sentence)
f.close()
f = open("testfile.txt", "r")
for s in f: print(s)
f.close()
Step 1: Write input.
Step 2: Loop read print.
Step 3: Output echoes.
Simple Way: For line in f.
Example 5: seek/tell Program 2-2 (Page 29)
Simple Explanation: Position control.
f = open("testfile.txt", "r+")
print(f.read()) # Full
print("Pos:", f.tell()) # 33
f.seek(0)
print("Begin:", f.tell()) # 0
f.seek(10)
print(f.read()) # Partial
Step 1: Read pos 33.
Step 2: Seek 10, partial read.
Step 3: Output as shown.
Simple Way: Random access.
Example 6: Pickle Dump/Load Program 2-7 (Page 33)
Simple Explanation: Object persist (2025 data science).
import pickle
lst = [1, "Geetika", "F", 26]
with open("mybinary.dat", "wb") as f:
pickle.dump(lst, f)
with open("mybinary.dat", "rb") as f:
data = pickle.load(f)
print(data)
Step 1: Dump wb.
Step 2: Load rb print.
Step 3: [1, 'Geetika', ...].
Simple Way: Serialize lists.
Tip: Run in shell; troubleshoot (e.g., no close buffer loss). Added for pickle, full programs.
Interactive Quiz - Master File Handling
10 MCQs in full sentences; 80%+ goal. Covers types, ops, pickle.
Quick Revision Notes & Mnemonics
Concise, easy-to-learn summaries for all subtopics. Structured in tables for quick scan: Key points, examples, mnemonics. Covers types, ops, pickle. Bold key terms; short phrases for fast reading.
Subtopic
Key Points
Examples
Mnemonics/Tips
Types
Text: ASCII chars, \n EOL (Page 20).
Binary: Bytes, app-specific.
Text readable, binary efficient.
.txt vs .dat; Activity 2.1.
TB (Text Bytes? No, Chars). Tip: "Text Talks, Binary Bytes" – Human vs machine.
Open/Close
open: name,mode; handle (Table 2.1).
close: Flush/free.
with: Auto.
"r" read begin; with safer.
OCW (Open-Close-With). Tip: "Open Wide, Close Tight" – Modes matter.
Write (w/wl)
write: Str, count return.
writelines: List, no \n auto.
Buffer flush.
Fig 2.1; "Hey\n"=41.
WWB (Write Writelines Buffer). Tip: "Write Words, Lines Lists" – Single vs multi.
Overall Tip: Use TB-OCW-RRR-TS-CT-DL for full scan (5 mins). Flashcards: Front (term), Back (points + mnemonic). Print table for wall revision. Covers 100% chapter – easy for exams!
Step-by-step breakdowns of core processes, structured as full questions followed by detailed answers with steps. Visual descriptions for easy understanding; focus on actionable Q&A with examples from chapter.
Question 1: How to create and write to a text file like Program 2-3?