File Handling in Python: CBSE Class 12 Computer Science Notes and Programs
Updated 14 October 2026 · Fact-checked
File handling lets a Python program store data permanently and read it back. Class 12 covers text files (open modes, write, writelines, read, readline, readlines, seek, tell), binary files with the pickle module (dump, load, search, append, update) and CSV files with the csv module (writer, writerow, writerows, reader), plus relative and absolute paths.
What File Handling in Python is about
File Handling in Python is the fourth chapter of Unit 1 and the one that carries the longest programs in the paper. The 2026-27 sample paper asks a 3-mark text-file function in Section C, a 4-mark CSV program in Section D and a 5-mark binary-file program (split 2 + 3) in Section E, on top of 1-mark MCQs on modes and methods.
What the syllabus lists:
- files and paths: why files are needed, text, binary and CSV files, relative and absolute paths
- text files: open modes r, r+, w, w+, a, a+; close(); the with clause; write() and writelines(); read(), readline() and readlines(); seek() and tell(); manipulating data in a text file (counting, searching, copying)
- binary files: modes rb, rb+, wb, wb+, ab, ab+; the pickle module with dump() and load(); read, write (create), search, append and update operations
- CSV files: the csv module; opening and closing; writer(), writerow(), writerows() and reader()
CSV is in the CBSE syllabus although the NCERT chapter does not cover it, and csv.DictReader and csv.DictWriter are not named, so this page uses only writer() and reader().
All programs below use three small files. notes.txt holds four lines:
Python is easy to learn.
Files store data permanently.
A text file stores characters.
Every line ends with a newline.student.dat holds three pickled lists [roll, name, marks]: [1, 'Asha', 88], [2, 'Ravi', 64], [3, 'Meena', 79]. items.csv holds a header row Code,Name,Price and the rows 101,Pen,20; 102,Notebook,45; 103,Bag,650.
Weightage: This chapter is part of Unit 1, Computational Thinking and Programming - 2, which carries 40 of the 70 theory marks together with Revision of Python Topics from Class XI, Functions, Exception Handling in Python and Stack.Source: CBSE Computer Science (083) syllabus 2026-27, distribution of marks, Unit 1 Computational Thinking and Programming - 2
Key concepts
- Files, file types and paths
- NCERT section NCERT 2.1, 2.2
Variables lose their values when a program ends; a file on secondary storage keeps data permanently. A text file stores characters (readable in Notepad), with each line ending in the newline character
\n; .txt and .py files are text files. A binary file stores data as raw bytes in the form the program uses (images, .dat files made with pickle) and is not human-readable. A CSV file (comma-separated values) is a text file in which each line is a record and commas separate the fields, so spreadsheets can open it. A path locates a file: an absolute path starts from the root of the drive (C:\School\CS\notes.txt), while a relative path starts from the current working folder (notes.txt,data\notes.txt,..\notes.txtwhere..is the parent folder).Worked example
The program runs in the folder
C:\School\CS. Give the absolute path ofmarks.csvstored inC:\School\CS\data, and a relative path to it. Which file type suits (a) a class register opened in a spreadsheet (b) a list of Python records saved as they are?Try it first, then show the solutionSolution
- Absolute: from the drive root,
C:\School\CS\data\marks.csv. - Relative: from the current folder
C:\School\CS, it isdata\marks.csv. - (a) A spreadsheet reads comma-separated text: a CSV file.
- (b) Python objects saved as they are with pickle: a binary file.
Answer: C:\School\CS\data\marks.csv and data\marks.csv; (a) CSV file (b) binary file.
- Absolute: from the drive root,
- Opening, closing and file modes
- NCERT section NCERT 2.3.1, 2.3.2
f = open(file_name, mode)returns a file object (file handle); the default mode is 'r'.f.close()saves any buffered data and frees the file. The modes:Mode Purpose If the file does not exist If it exists Starts at r read only FileNotFoundError kept beginning r+ read and write FileNotFoundError kept (writing overwrites in place) beginning w write only created emptied (truncated) beginning w+ write and read created emptied beginning a append only created kept end a+ append and read created kept end Add b for binary files: rb, rb+, wb, wb+, ab, ab+. In a and a+ every write goes to the end of the file.
Worked example
notes.txt exists. Which modes (i) destroy its contents on opening, (ii) raise an error if the file is missing, (iii) let you read and also add text at the end?
Try it first, then show the solutionSolution
- w and w+ truncate an existing file (wb and wb+ for binary files).
- r and r+ need the file to exist; otherwise FileNotFoundError.
- a+ opens for reading and appending (writes go to the end).
Answer: (i) w, w+ (ii) r, r+ (iii) a+
- The with clause
- NCERT section NCERT 2.3.3
with open('notes.txt', 'r') as f:opens the file and closes it automatically when the indented block ends, even if an exception occurs inside it. So you do not write close(). After the block, f still exists as a name but the file is closed, and reading from it raises ValueError (I/O operation on closed file).Worked example
Rewrite with the with clause:
f = open('log.txt', 'a') f.write('Backup done\n') f.close()Try it first, then show the solutionSolution
- The with statement replaces both open-and-assign and close().
with open('log.txt', 'a') as f: f.write('Backup done\n')
Answer: The two-line with version; the file is closed automatically at the end of the block.
- Writing: write() and writelines()
- NCERT section NCERT 2.4
f.write(s)writes the string s and returns the number of characters written. It does not add a newline: put\nyourself. It accepts only a string, so numbers needstr().f.writelines(seq)writes every string in a list or tuple one after the other, also without adding newlines, and returns None.Worked example
What does this print, and what does notes.txt contain afterwards?
f = open('notes.txt', 'w') n = f.write('Python is easy to learn.\nFiles store data permanently.\n') f.writelines(['A text file stores characters.\n', 'Every line ends with a newline.\n']) f.close() print(n)Try it first, then show the solutionSolution
- 'w' empties the file first.
- The first string has 24 + 1 characters in line 1 and 29 + 1 in line 2 (each \n counts as one character): 25 + 30 = 55, which write() returns.
- writelines() adds the two strings exactly as given.
Answer: It prints 55; notes.txt then holds the four lines shown in the overview.
- Reading: read(), readline() and readlines()
- NCERT section NCERT 2.5
f.read()returns the whole remaining file as one string;f.read(n)returns at most n characters.f.readline()returns one line including its\n(or the rest of the line if part was already read);f.readline(n)returns at most n characters of the line.f.readlines()returns a list of all remaining lines, each with its\n. At the end of the file, read() and readline() return''and readlines() returns[]. Each read moves the file pointer forward, so the next read continues where the last one stopped.for line in f:reads one line per pass and is the usual way to process a file line by line.Worked example
Predict the output (notes.txt as in the overview):
with open('notes.txt') as f: print(f.read(6)) print(f.readline(), end='') print(f.readline(5)) rest = f.readlines() print(len(rest))Try it first, then show the solutionSolution
- read(6) returns 'Python'.
- readline() returns the rest of line 1: ' is easy to learn.\n'; end='' avoids a second newline.
- readline(5) returns the first 5 characters of line 2: 'Files'.
- readlines() returns the remainder of line 2 plus lines 3 and 4: three items.
Answer: Python
is easy to learn.
Files
3- seek() and tell()
- NCERT section NCERT 2.6
The file pointer marks where the next read or write happens.
f.tell()returns its position as a number of bytes from the start.f.seek(offset, reference_point)moves it: reference point 0 = from the beginning (the default), 1 = from the current position, 2 = from the end. In text mode onlyseek(n)/seek(n, 0)andseek(0, 2)are allowed; non-zero offsets from 1 or 2 need binary mode. Note: tell() counts bytes, and on Windows a text file stores each newline as two bytes, so tell() values there can be larger than a character count.Worked example
Predict the output:
with open('notes.txt') as f: f.seek(10) print(f.read(4), f.tell()) f.seek(0) print(f.readline().strip())Try it first, then show the solutionSolution
- Line 1 is 'Python is easy to learn.': index 10 is the 'e' of 'easy' (P0 y1 t2 h3 o4 n5 space6 i7 s8 space9 e10).
- read(4) gives 'easy' and the pointer moves to 14.
- seek(0) goes back to the start; readline().strip() gives line 1 without its newline.
Answer: easy 14
Python is easy to learn.- Manipulating data in a text file
- NCERT section NCERT 2.7
Board functions on text files follow one pattern: open in 'r' mode, read with read(), readlines() or a for loop, test each word, line or character, and count or display. Use
read().split()for words,for line in forreadlines()for lines, and a loop overread()for characters. To change a file, read it, build the new text, and write it to the same or another file (there is no in-place edit of a line in a text file).Worked example
Write a function COUNT_AE() that counts the lines of notes.txt beginning with 'A' or 'E' (either case) and returns the count.
Try it first, then show the solutionSolution
- Read line by line and test the first character.
def COUNT_AE(): c = 0 with open('notes.txt') as f: for line in f: if line[0] in 'AaEe': c += 1 return c print(COUNT_AE())- Lines 3 ('A text...') and 4 ('Every...') qualify.
Answer: 2
- Binary files with pickle: dump() and load()
- NCERT section NCERT 2.8
Pickling (serialisation) turns a Python object into a byte stream; unpickling turns it back.
import pickle, thenpickle.dump(obj, f)writes one object to a file opened in 'wb' or 'ab', andpickle.load(f)reads the next object from a file opened in 'rb'. Each dump adds one object; load() reads them in the same order. When no object is left, load() raises EOFError, so reading all records uses a loop inside try-except EOFError. You can also store a whole list of records with a single dump and get it back with a single load.Worked example
Write display() to print every record of student.dat.
Try it first, then show the solutionSolution
- Open in 'rb'; load in an endless loop; stop at EOFError.
import pickle def display(): with open('student.dat', 'rb') as f: try: while True: rec = pickle.load(f) print(rec) except EOFError: pass display()
Answer: [1, 'Asha', 88]
[2, 'Ravi', 64]
[3, 'Meena', 79]- Binary files: search, append and update
- NCERT section NCERT 2.8.3
Search: load every record and compare a field, keeping a flag to print 'not found' at the end. Append: open in 'ab' and dump the new record; existing records stay. Update: the safe method reads all records into a list, changes the matching one, and rewrites the file in 'wb'. A second method opens in 'rb+', notes
pos = f.tell()before each load, and on a match doesf.seek(pos)and dumps the changed record over the old one; this works only if the new record pickles to the same number of bytes.Worked example
Write update(roll, new_marks) that changes the marks of the student with the given roll number in student.dat, using the read-all-and-rewrite method. Show the file after update(2, 70).
Try it first, then show the solutionSolution
import pickle def update(roll, new_marks): recs = [] with open('student.dat', 'rb') as f: try: while True: recs.append(pickle.load(f)) except EOFError: pass for r in recs: if r[0] == roll: r[2] = new_marks with open('student.dat', 'wb') as f: for r in recs: pickle.dump(r, f) update(2, 70) with open('student.dat', 'rb') as f: for i in range(3): print(pickle.load(f))- All three records are read, Ravi's marks become 70, and all three are written back.
Answer: [1, 'Asha', 88]
[2, 'Ravi', 70]
[3, 'Meena', 79]- CSV files with the csv module
- NCERT section Not in NCERT; CBSE syllabus (CSV file)
import csv. Open withnewline=''when writing, so that no blank lines appear between rows on Windows. Writing:w = csv.writer(f)makes a writer object;w.writerow(list)writes one row;w.writerows(list_of_lists)writes many rows. A different separator can be chosen withcsv.writer(f, delimiter='|'). Reading:r = csv.reader(f)gives an object that yields each row as a list of strings, so numbers must be converted with int() or float(). Skip the header row withnext(r)(or by ignoring the first row in a loop).Worked example
Write code that reads items.csv, skips the header, prints the names of items costing more than 30 and the total of all prices.
Try it first, then show the solutionSolution
- Each row is a list of strings, so convert the price with int().
import csv with open('items.csv') as f: r = csv.reader(f) next(r) total = 0 for row in r: if int(row[2]) > 30: print(row[1], end=' ') total += int(row[2]) print(total)- Notebook (45) and Bag (650) cost more than 30; total = 20 + 45 + 650 = 715.
Answer: Notebook Bag 715
File Handling in Python in real life
Each concept, met in an everyday situation. Read the situation, answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.
Append mode
Suppose a school gate app writes one line to visitors.txt each time a visitor signs in, and the file must keep every earlier entry.
Which mode should the app open the file in, and what single statement writes the entry 'Ravi, 10:15'?
Try it first, then show the solutionSolution
- 'w' would erase earlier visitors each time; 'a' creates the file the first time and adds to the end afterwards.
with open('visitors.txt', 'a') as f: f.write('Ravi, 10:15\n') print(open('visitors.txt').read(), end='')
Answer: Mode 'a'; f.write('Ravi, 10:15\n') (the program prints Ravi, 10:15).
Memory hook: a for attendance register: always written at the bottom.
CSV for spreadsheets
Imagine the sports teacher wants the house-wise points exported from a Python program so the office can open them in a spreadsheet.
Write code that creates points.csv with a header and two rows, then reads it back.
Try it first, then show the solutionSolution
- Write with csv.writer and newline=''.
import csv with open('points.csv', 'w', newline='') as f: w = csv.writer(f) w.writerow(['House', 'Points']) w.writerows([['Red', 120], ['Blue', 95]]) with open('points.csv') as f: for row in csv.reader(f): print(row)- reader() returns every field as a string, including the numbers.
Answer: ['House', 'Points']
['Red', '120']
['Blue', '95']
Memory hook: CSV = a spreadsheet saved as plain text with commas.
pickle for records
Suppose a library program keeps each book as a list [id, title, issued] and must save the list exactly so the next day's run can continue.
Why use a binary file with pickle instead of a text file, and how do you read all books back?
Try it first, then show the solutionSolution
- pickle stores the Python list as it is and returns a list on loading; a text file would need converting every field to and from strings.
- Read back with pickle.load() in a while True loop until EOFError.
Answer: pickle keeps the record's structure and types; read with repeated load() until EOFError.
Memory hook: Pickle preserves the object, like pickling preserves a mango.
Topics in this chapter
File Handling in Python: syntax and key facts
- Open and close
f = open('name', 'mode')...f.close(), orwith open('name', 'mode') as f:(closes automatically)- Default mode is 'r'. Binary modes add b: rb, wb, ab, rb+, wb+, ab+.
- Text modes in one line
r / r+ must exist, pointer at start w / w+ create or truncate a / a+ create or keep, writes at the end - + adds the other operation. Opening an existing file in w mode erases it.
- Write methods
f.write(str)returns the number of characters;f.writelines(list_of_str)returns None; neither adds\n- Convert numbers with str() before writing to a text file.
- Read methods
read()/read(n): string;readline()/readline(n): one line with\n;readlines(): list of lines- At end of file: '' for read and readline, [] for readlines.
- Pointer methods
f.tell(): current byte position;f.seek(offset, ref): ref 0 start (default), 1 current, 2 end- Text mode allows seek(n) from the start and seek(0, 2); other relative seeks need binary mode.
- pickle
pickle.dump(obj, f)in wb / ab;obj = pickle.load(f)in rb; loop until EOFError- One dump writes one object; one load reads one object.
- csv
csv.writer(f),.writerow(row),.writerows(rows);csv.reader(f)yields each row as a list of strings- Use newline='' with open() when writing a CSV file.
How the board asks File Handling in Python
The question patterns to expect, and the method that works for each.
| Question type | How it is asked | Method |
|---|---|---|
| Text-file function (count or display) | "Write a function that counts the words/lines/characters in a file that..." or "displays the lines that..." (3 marks, Section C). | Header with the given name, open in 'r' (preferably with), choose read().split() for words, a for loop for lines, then the test and the count; return or print as asked. |
| Binary-file program with pickle | A record structure is given, e.g. [roll, name, marks]; write functions to add records and to search, count, copy or update them (5 marks split 2 + 3, Section E). | import pickle; write with dump in 'ab' or 'wb'; read with load in a while True loop inside try-except EOFError; for update, read all into a list and rewrite in 'wb'. |
| CSV program | Write functions to add a row and to read rows meeting a condition, e.g. count items above a price (4 marks, Section D). | import csv; append with open(..., 'a', newline='') and writer().writerow(); read with reader(), skip the header, convert numeric strings with int(). |
| Modes and methods MCQ | Which mode creates a file if absent and keeps old data? What does readlines() return? What is the default reference point of seek()? (1 mark). | Use the modes table: existence, truncation and starting position decide the answer. |
| Output with read methods, seek and tell | File contents are given with a sequence of read(n), readline(), seek() and tell() calls (1-2 marks). | Number the characters of the first lines; move a pointer through them call by call, counting each newline as one character. |
| Theory: text vs binary vs CSV, relative vs absolute path | Differentiate with examples (2 marks). | Two points each: what is stored and whether it is human-readable; give a file name example for each. |
Tricks to remember File Handling in Python
Short memory aids. Say each one aloud once, then use it on a question the same day.
W wipes, A adds, R requires
w wipes an existing file, a adds at the end, r requires the file to exist.
Use it when: Every modes MCQ.
Plus means both
r+, w+ and a+ all read and write; the letter before + decides creation, truncation and starting point.
Use it when: Choosing between r+, w+ and a+.
readline keeps the newline
Every line from readline() or readlines() still ends in \n, so print it with end='' or strip() it.
Use it when: Output questions that show blank lines.
Dump to save, Load to bring back
dump(object, file) has the object first, like putting something into a box; load(file) takes it out.
Use it when: Remembering the argument order of pickle.dump().
CSV reader gives strings
Everything that comes out of csv.reader is a string, even 650.
Use it when: Comparisons and totals in CSV programs.
Seek 0-1-2 = Start-Current-End
Reference points count like a race: 0 at the start line, 1 where you are now, 2 at the finish.
Use it when: seek() questions.
File Handling in Python: board-level solved questions
Ordered from board level to HOTS. Cover the solution, write your own, then compare step by step.
Example 1: Read methods in sequence · 2 marks · Short answerHarder board level
notes.txt is as in the overview. Predict the output:
f = open('notes.txt')
x = f.readline()
y = f.read(5)
z = f.readlines()
print(len(x), y, len(z))
print(z[0].split()[0])
f.close()Try it first, then show the solutionSolution
- x = 'Python is easy to learn.\n', 25 characters.
- y = the first 5 characters of line 2: 'Files'.
- z = [' store data permanently.\n', line 3, line 4]: 3 items.
- z[0].split() is ['store', 'data', 'permanently.'], whose first item is 'store'.
Answer: 25 Files 3
store
Example 2: Count words of each length · 3 marks · Short answerHarder board level
Write a function LONGWORDS() that displays the words of notes.txt having more than 7 characters, and give its output.
Try it first, then show the solutionSolution
- Words are separated by whitespace, so read().split() gives them (punctuation stays attached).
def LONGWORDS(): with open('notes.txt') as f: for w in f.read().split(): if len(w) > 7: print(w, end=' ') LONGWORDS()- 'permanently.' (12), 'characters.' (11) and 'newline.' (8) qualify; 'Python' (6) and 'stores' (6) do not.
Answer: permanently. characters. newline.
Example 3: Modes that look alike · 1 mark · MCQHOTS / competency
notes.txt exists. After running
f = open('notes.txt', 'w+')
f.write('Hello')
f.seek(0)
print(f.read())
f.close()
f = open('notes.txt', 'r+')
f.write('J')
f.seek(0)
print(f.read())
f.close()what is printed? (a) Hello / Jello (b) Hello / JHello (c) Python... / Jello (d) Hello / J
Try it first, then show the solutionSolution
- w+ erases the four lines; the file holds 'Hello'; seek(0) and read() print Hello.
- r+ keeps the content and starts at position 0; writing 'J' overwrites the 'H' (it does not insert).
- Reading from the start gives 'Jello'.
Answer: (a) Hello and then Jello
Example 4: Binary file: count and append · 5 marks · Long answerHarder board level
student.dat holds records [roll, name, marks]. (a) Write add_student(rec) to append a record. (b) Write count_above(m) to return the number of students scoring more than m. Show count_above(75) after add_student([4, 'Joy', 91]).
Try it first, then show the solutionSolution
- (a) Appending uses 'ab' so existing records stay.
- (b) Read every record until EOFError and count the matches.
import pickle def add_student(rec): with open('student.dat', 'ab') as f: pickle.dump(rec, f) def count_above(m): c = 0 with open('student.dat', 'rb') as f: try: while True: rec = pickle.load(f) if rec[2] > m: c += 1 except EOFError: pass return c add_student([4, 'Joy', 91]) print(count_above(75))- Marks 88, 64, 79, 91: three are above 75.
Answer: 3
Example 5: Update in place with rb+ · 3 marks · Short answerHOTS / competency
Write update2(roll, new_marks) that updates a record of student.dat in place using rb+, tell() and seek(). Show update2(3, 81).
Try it first, then show the solutionSolution
- Remember the start position of each record before loading it; on a match, go back there and dump the changed record over the old one.
import pickle def update2(roll, new_marks): with open('student.dat', 'rb+') as f: try: while True: pos = f.tell() rec = pickle.load(f) if rec[0] == roll: rec[2] = new_marks f.seek(pos) pickle.dump(rec, f) print('updated') break except EOFError: print('not found') update2(3, 81)- This is safe here because 79 and 81 pickle to the same number of bytes; if the new record were longer it would overwrite the next record, which is why the read-all-and-rewrite method is safer.
Answer: updated (Meena's record becomes [3, 'Meena', 81])
Example 6: CSV add and count · 4 marks · Long answerHarder board level
Write ADD_ITEM(code, name, price) to add a row to items.csv and COUNT_COSTLY() to return the number of items priced above 100. Show COUNT_COSTLY() after ADD_ITEM(104, 'Calculator', 450).
Try it first, then show the solutionSolution
- Append with mode 'a' and newline=''; read with reader() and skip the header.
import csv def ADD_ITEM(code, name, price): with open('items.csv', 'a', newline='') as f: w = csv.writer(f) w.writerow([code, name, price]) def COUNT_COSTLY(): c = 0 with open('items.csv') as f: r = csv.reader(f) next(r) for row in r: if int(row[2]) > 100: c += 1 return c ADD_ITEM(104, 'Calculator', 450) print(COUNT_COSTLY())- Prices now: 20, 45, 650, 450; two are above 100.
Answer: 2
Example 7: Assertion-reason on pickle · 1 mark · Assertion-reasonHOTS / competency
Assertion (A): A loop that reads all records of a binary file with pickle.load() is written inside a try block.
Reason (R): pickle.load() raises EOFError when it reaches the end of the file.
(a) Both true, R explains A (b) Both true, R does not explain A (c) A true, R false (d) A false, R true
Try it first, then show the solutionSolution
- The loop has no natural end, so the program relies on catching the exception load() raises at the end of file.
- That exception is EOFError, which is exactly what R says.
Answer: (a) Both A and R are true and R is the correct explanation of A.
Example 8: seek and tell trace · 2 marks · Short answerHarder board level
Predict the output:
f = open('notes.txt')
print(f.read(6), f.tell())
f.seek(15)
print(f.read(5))
f.seek(0)
print(len(f.readline()), f.tell())
f.close()Try it first, then show the solutionSolution
- read(6) gives 'Python'; the pointer is at 6.
- Number line 1: P0 y1 t2 h3 o4 n5 (space)6 i7 s8 (space)9 e10 a11 s12 y13 (space)14 t15 o16 (space)17 l18 e19. seek(15) puts the pointer on 't', so read(5) gives 'to le'.
- seek(0) then readline() returns line 1 with its newline: 25 characters; the pointer is now at 25.
Answer: Python 6
to le
25 25
Case-study practice (Section E style)
Read the situation, then answer every part. In the board paper this is a 4-mark question split into 1 + 1 + 2 marks.
Library visitor log
Suppose the school library keeps a text file visitors.txt in which every line is 'Name,Class', for example:
Asha,12A
Ravi,11B
Meena,12CThe librarian wants small Python functions to manage it.
(i) · 1 mark
Which mode should be used to add a new visitor without losing earlier lines?
Answer
Answer: 'a' (append)
It creates the file if needed and writes at the end.
(ii) · 1 mark
What does readlines() return for this file?
Answer
Answer: ['Asha,12A\n', 'Ravi,11B\n', 'Meena,12C\n']
A list of lines, each ending in a newline.
(iii) · 2 marks
Write a function CLASS12() that counts the visitors from Class 12 and returns the count.
Answer
Answer:
Output: 2 (the first three lines only create the sample file)with open('visitors.txt', 'w') as f: f.write('Asha,12A\nRavi,11B\nMeena,12C\n') def CLASS12(): c = 0 with open('visitors.txt') as f: for line in f: name, cls = line.strip().split(',') if cls.startswith('12'): c += 1 return c print(CLASS12())strip() removes the newline; split(',') separates the name and class; startswith('12') selects Class 12.
Where the marks are
How a typical answer is split into step marks. Show every step: a right final answer alone rarely earns full marks.
Differentiate between the w and a modes of opening a text file, with one statement each. [2 marks] (2 marks)
| Step | Marks |
|---|---|
w creates the file or erases an existing one and writes from the start, e.g. open('log.txt', 'w') | 1 |
a creates the file if absent but keeps existing data and writes at the end, e.g. open('log.txt', 'a') | 1 |
Write a function LONGWORDS() that displays the words of notes.txt having more than 7 characters. [3 marks] (3 marks)
| Step | Marks |
|---|---|
| Opening notes.txt in read mode (and closing it or using with) | 1 |
| Reading the words with read().split() | 1 |
| Testing len(w) > 7 and displaying the word | 1 |
Write ADD_ITEM(code, name, price) to append a row to items.csv, and COUNT_COSTLY() to return the number of items with price above 100. [4 marks] (4 marks)
| Step | Marks |
|---|---|
| ADD_ITEM: open in 'a' with newline='' and create csv.writer | 1 |
| writerow([code, name, price]) | 1 |
| COUNT_COSTLY: open, csv.reader and skip the header | 1 |
| int(row[2]) > 100 test, counting and returning | 1 |
A binary file student.dat holds records [roll, name, marks]. (a) Write add_student(rec) to append a record. (b) Write count_above(m) to return the number of students with marks above m. [2 + 3 = 5 marks] (5 marks)
| Step | Marks |
|---|---|
| (a) import pickle and open in 'ab' | 1 |
| (a) pickle.dump(rec, f) | 1 |
| (b) open in 'rb' and the while True loop with pickle.load() | 1 |
| (b) try-except EOFError to stop | 1 |
| (b) comparing rec[2] > m, counting and returning | 1 |
Where students lose marks in File Handling in Python
The slips examiners see most often, and what to write instead.
Mistake: Comparing a CSV field with a number without converting it
reader() gives strings, and comparing a str with an int raises TypeError (or compares text if both are strings).
Wrong working
if row[2] > 30:
Right working
if int(row[2]) > 30:
Do this: Convert every numeric field with int() or float() before comparing or adding.
Usually costs: 1 mark in a 4-mark CSV question
Mistake: Reading a binary file without handling EOFError
The while True loop has no other way to stop; without try-except the program crashes at the end of the file.
Wrong working
while True:
rec = pickle.load(f)
print(rec)Right working
try:
while True:
rec = pickle.load(f)
print(rec)
except EOFError:
passDo this: Always wrap the load loop in try-except EOFError (or store all records as one list and load once).
Usually costs: 1 mark
Mistake: Using 'w' or 'wb' to add a record to an existing file
w truncates the file, so every old record is lost.
Do this: Use 'a' (text, CSV) or 'ab' (binary) for adding; use 'w' only to create or rewrite the whole file.
Usually costs: 1 mark
Mistake: Counting words with split('\n') or lines with split()
split() with no argument splits on all whitespace (words); lines need readlines() or a for loop.
Wrong working
words = f.read().split('\n')
Right working
words = f.read().split()
Do this: Words: read().split(). Lines: readlines() or for line in f. Characters: a loop over read().
Usually costs: 1-2 marks
Mistake: Forgetting that readline() returns the newline
A test such as
line == 'END'fails because the line is 'END\n', and printing adds an extra blank line.Do this: Use line.strip() (or rstrip('\n')) before comparing, and print(line, end='') when printing raw lines.
Usually costs: Half to 1 mark
Mistake: Writing a number directly with write()
write() accepts only strings; f.write(45) raises TypeError.
Wrong working
f.write(marks)
Right working
f.write(str(marks) + '\n')
Do this: Convert with str() and add the newline yourself.
Usually costs: Half a mark
NCERT exercise guide: File Handling in Python
What each exercise in the NCERT chapter tests, how to approach it, and a question of the same kind solved step by step. Questions here are written in our own words.
NCERT Chapter 2 exercises: theory on files, modes and methods
What it tests: Text versus binary files, the purpose of each mode, read() versus readline() versus readlines(), write() versus writelines(), seek() and tell().
How to approach it: Answer differences point by point (what it does, what it returns) with a one-line example.
Same kind as the read() / readline() / readlines() exercise
For notes.txt, what does each statement print when it is the first read after opening? (a) print(len(f.read())) (b) print(f.readline()) (c) print(len(f.readlines()))
Show the solutionSolution
- (a) Characters: 25 + 30 + 31 + 32 = 118 (each line's \n included).
- (b) The first line with its newline: 'Python is easy to learn.' followed by an extra blank line from print().
- (c) Four lines in the list.
Answer: (a) 118 (b) Python is easy to learn. and a blank line (c) 4
NCERT Chapter 2 exercises: programs on text files
What it tests: Writing user input to a file and reading it back; counting and displaying from a file.
How to approach it: Write in 'w' or 'a' with \n after each entry; read back with a for loop.
Same kind as the copy-and-filter programs
Copy every line of notes.txt that contains the word 'text' (any case) into a file text_lines.txt and print how many lines were copied.
Show the solutionSolution
c = 0 with open('notes.txt') as src, open('text_lines.txt', 'w') as dst: for line in src: if 'text' in line.lower(): dst.write(line) c += 1 print(c)- Only line 3, 'A text file stores characters.', contains 'text'.
Answer: 1
NCERT Chapter 2 exercises: pickle programs
What it tests: Writing objects with dump(), reading with load(), and processing records.
How to approach it: Decide the record structure, then write the add and read functions separately.
Same kind as the pickle exercises
Write search(roll) for student.dat that prints the record with the given roll number, or 'No record'. Show search(2) and search(9).
Show the solutionSolution
import pickle def search(roll): found = False with open('student.dat', 'rb') as f: try: while True: rec = pickle.load(f) if rec[0] == roll: print('Found:', rec) found = True except EOFError: pass if not found: print('No record') search(2) search(9)
Answer: Found: [2, 'Ravi', 64]
No record
Practice questions on File Handling in Python
Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.
Q1 · 1 mark · MCQBoard level
Which mode opens a binary file for both reading and writing without erasing it? (a) wb+ (b) rb+ (c) ab (d) wb
Hint
Truncation comes from w.
Answer
(b) rb+
Q2 · 1 mark · Very short answerBoard level
What does
f.writelines(['a', 'b'])write, and what does it return?Hint
No newlines are added.
Answer
It writes 'ab' and returns None.
Q3 · 3 marks · Short answerBoard level
Write a function COUNT_THE() that counts how many times the word 'the' (any case) occurs as a whole word in a text file story.txt.
Hint
Compare each word in lower case.
Answer
with open('story.txt', 'w') as f: f.write('The cat saw the dog.\nThen the end.\n') def COUNT_THE(): c = 0 with open('story.txt') as f: for w in f.read().split(): if w.lower() == 'the': c += 1 return c print(COUNT_THE())Output for this sample: 3 ('Then' and 'dog.' do not match). The first two lines only create a sample file.
Q4 · 2 marks · Short answerHarder board level
Predict the output (notes.txt as in the overview):
with open('notes.txt') as f: L = f.readlines() print(len(L), L[1][:5], L[-1].split()[-1])Hint
The last word keeps its full stop.
Answer
4 Files newline.
Q5 · 3 marks · Short answerHarder board level
Write a function DISPLAY_UPPER() that displays the lines of notes.txt that contain more than four words, in upper case.
Hint
len(line.split()) > 4.
Answer
def DISPLAY_UPPER(): with open('notes.txt') as f: for line in f: if len(line.split()) > 4: print(line.upper(), end='') DISPLAY_UPPER()Output:
PYTHON IS EASY TO LEARN.
A TEXT FILE STORES CHARACTERS.
EVERY LINE ENDS WITH A NEWLINE.Q6 · 3 marks · Short answerHOTS / competency
student.dat holds records [roll, name, marks]. Write COPY_TOPPERS() that copies records with marks 80 or more into toppers.dat and returns how many were copied.
Hint
Open one file in rb and the other in wb.
Answer
import pickle def COPY_TOPPERS(): c = 0 with open('student.dat', 'rb') as src, open('toppers.dat', 'wb') as dst: try: while True: rec = pickle.load(src) if rec[2] >= 80: pickle.dump(rec, dst) c += 1 except EOFError: pass return c print(COPY_TOPPERS())Output: 1 (only Asha, 88)
Q7 · 2 marks · Short answerHarder board level
Write SHOW_CHEAP() to display the code and name of every item in items.csv priced below 50, one per line.
Hint
Skip the header row.
Answer
import csv def SHOW_CHEAP(): with open('items.csv') as f: r = csv.reader(f) next(r) for row in r: if int(row[2]) < 50: print(row[0], row[1]) SHOW_CHEAP()Output:
101 Pen
102 NotebookQ8 · 1 mark · Assertion-reasonHOTS / competency
Assertion (A): Opening an existing file in 'a+' mode and immediately calling read() returns an empty string.
Reason (R): In 'a+' mode the file pointer is placed at the end of the file.Hint
Where does reading start in a+?
Answer
(a) Both A and R are true and R is the correct explanation of A. Call seek(0) before reading.
Q9 · 2 marks · Short answerHarder board level
Write a function VOWEL_COUNT() that returns the number of vowels (any case) in notes.txt, character by character.
Hint
Loop over read().
Answer
def VOWEL_COUNT(): c = 0 with open('notes.txt') as f: for ch in f.read(): if ch.lower() in 'aeiou': c += 1 return c print(VOWEL_COUNT())Output: 35
Q10 · 2 marks · Short answerHOTS / competency
What is the difference between
csv.writer(f).writerow(L)andcsv.writer(f).writerows(L)when L = [[1, 'A'], [2, 'B']]?Hint
writerow() treats each item of L as one field.
Answer
writerows(L) writes two rows: 1,A and 2,B. writerow(L) writes one row whose two fields are the strings of the inner lists: "[1, 'A']","[2, 'B']".
Test your recall
Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.
1.Which mode opens a text file for reading and writing without erasing it, and fails if it does not exist?Show answer
r+
2.What does write() return?Show answer
The number of characters written.
3.What does readlines() return at the end of a file?Show answer
An empty list [].
4.What is the default reference point of seek()?Show answer
0, the beginning of the file.
5.Which exception tells a pickle.load() loop that the file has ended?Show answer
EOFError.
6.In what form does csv.reader() return each row?Show answer
As a list of strings.
7.Why is newline='' used when opening a CSV file for writing?Show answer
To stop blank lines appearing between rows (the csv module writes its own line endings).
8.Give one difference between a relative and an absolute path.Show answer
An absolute path starts from the drive root (C:\...); a relative path starts from the current working folder.
9.Which method writes several rows to a CSV file at once?Show answer
writerows() of a csv.writer object.
Best order to study it
- Why files, the three file types, and relative versus absolute paths.
- open(), close(), the with clause and the six text modes (learn the table).
- write() and writelines(); then read(), readline(), readlines() and the for loop.
- seek() and tell() with a character-numbered line.
- Text manipulation functions: count words, lines, characters; display lines that match.
- Binary files: dump, load, the EOFError loop; then search, append and update.
- CSV: writer, writerow, writerows, reader; convert strings to numbers.
Quick revision checklist
The night before the exam: can you do each of these without looking?
- Text file: characters and lines; binary file: bytes (pickle); CSV: text with comma-separated fields.
- Absolute path starts from the drive root; relative path from the current folder.
- r/r+ need the file; w/w+ create or erase; a/a+ create or keep and write at the end.
- with open(...) as f: closes the file automatically.
- write() returns characters written; writelines() writes a list of strings; neither adds \n.
- read() string; readline() one line with \n; readlines() list of lines.
- tell() gives the pointer position; seek(n) moves it n bytes from the start.
- pickle.dump(obj, f) in wb/ab; pickle.load(f) in rb; stop at EOFError.
- Update a binary file: read all, change, rewrite in wb (or rb+ with tell and seek).
- csv.writer(f).writerow(row)/writerows(rows); csv.reader(f) gives lists of strings; open with newline=''.
File Handling in Python: frequently asked questions
Which file-handling questions carry the most marks in CBSE Class 12 Computer Science?
In the 2026-27 sample paper, a binary-file program with pickle is a 5-mark Section E question (split 2 + 3), a CSV program is a 4-mark Section D question, and a text-file function is a 3-mark Section C question. File modes and methods also appear as 1-mark MCQs.
Is csv.DictReader in the CBSE syllabus?
No. The 2026-27 syllabus names writer(), writerow(), writerows() and reader() only, so write CSV answers with those.
Do I have to use the with clause?
No. open() with close() is equally correct. The with clause is shorter and closes the file automatically, so it avoids losing marks for a missing close().
How do I update a record in a binary file?
The safe method: load all records into a list, change the matching record, and write all records back with 'wb'. The rb+ method with tell() and seek() overwrites the record in place, but only works when the new record has the same pickled size.
What is the difference between a text file and a binary file?
A text file stores characters with line endings and can be read in any text editor. A binary file stores bytes exactly as the program uses them (for example pickled lists), is not human-readable, and is read and written in rb/wb/ab modes.
Is the CSV file in the NCERT book?
No. The NCERT chapter covers text and binary files; CSV files are in the CBSE syllabus, so learn them from the syllabus list: the csv module, writer(), writerow(), writerows() and reader().
Based on: CBSE Computer Science (083) syllabus 2026-27; NCERT Computer Science, Textbook for Class XII (Reprint 2026-27)