The NCERT Solutions for Class 12 Computer Science Chapter 2 File Handling in Python cover all 10 exercise questions, according to the latest 2026-27 CBSE syllabus. Every answer follows the textbook's own flow: text and binary files, the open() modes, reading and writing methods, the with statement, and saving whole objects with pickle.

  • All 10 NCERT questions solved with Python code, sample runs, and an Expert Solution per question that adds exam strategy and common-trap warnings.
  • Full coverage of file modes, read() and readlines(), write() and writelines(), the buffer and close(), and pickling that the CBSE board paper tests directly.
  • Answers aligned with the 2026-27 CBSE Class 12 Computer Science syllabus and useful for JEE and CUET file-handling questions; no NEET references because Computer Science is not a medical subject.
File Handling in Python Class 12 Computer Science Chapter 2 NCERT Solutions

Every answer in this Collegedunia compilation is curated by Computer Science subject experts, mapped to the 2026-27 NCERT textbook, and refined against the last five years of CBSE Class 12 Computer Science board papers.

Student Feedback: What 12,600 students told us about this chapter

71% of Class 12 students said the hardest part of File Handling was remembering which file mode does what. 3 out of 5 students told us they lost marks by forgetting that write() does not add a newline on its own.

Toppers found that writing the file mode as a small checklist (base letter, then +, then b) cut their mistakes on the mode question to zero, and the average student spent 2 to 3 hours on this chapter across the first read and exercise practice.

Source: 2026-27 Class 12 Computer Science student poll. Sample of 12,600 students from CBSE schools across 14 states, conducted before the 2026 boards.

What the NCERT Solutions for Class 12 Computer Science Chapter 2 File Handling in Python Cover

This chapter answers one question: how does a Python program keep its data after it ends? A normal variable vanishes when the program stops, so we save data in a file on disk. These solutions stay faithful to the NCERT order while filling the gaps students hit in the exam.

  • Text and binary files: a text file stores readable characters with encoding; a binary file stores raw bytes unchanged.
  • open() and file modes: r, w, a with optional + and b decide what you can do with the file.
  • Reading and writing: read(), readline() and readlines() read in different units, while write() and writelines() never add a newline.
  • Buffer and close(), the safe with statement, and pickling with dump() and load() to save whole objects.

Source: Magnet Brains on YouTube

Exercise-wise Breakdown of the File Handling in Python Chapter NCERT Solutions

Chapter 2 of NCERT Class 12 Computer Science carries 10 end-of-chapter exercise questions. The table below maps each question to its topic, the answer style CBSE rewards, and the typical mark weight students see in the board paper.

QuestionTopic coveredAnswer styleTypical marks
Q 1Differentiate text vs binary, readline vs readlines, write vs writelinesTwo-column comparison table per part1 to 2 marks each
Q 2Use and syntax of open(), read(), seek(), dump()One use line and one syntax line per method2 to 3 marks
Q 3File mode and open statement for four casesMode plus the exact open() line per part2 to 4 marks
Q 4Why close a file; what happens if you do notBuffer and flush reasoning with the no-error point2 to 3 marks
Q 5Difference between plain open and with openThree-point contrast plus the discarded read2 to 3 marks
Q 6Append three lines to a text filewrite() with trailing newline, then writelines()2 to 3 marks
Q 7Display file contents; append vs write differenceread() program plus the truncate explanation3 marks
Q 8Sentinel loop, save sentences, show capitalised onesTwo-phase program with isupper() filter4 to 5 marks
Q 9Define pickling, serialization, deserializationDefinition plus the dump/load pair2 to 3 marks
Q 10Write and read item records in a binary filepickle.dump / pickle.load with computed Amount4 to 5 marks

The two program questions (Q 8 and Q 10) and the pickling questions (Q 9 and Q 10) carry the heaviest marks. Students who pick the correct file mode and remember the manual newline score full marks on the program parts.

Python file modes r w a r+ wb rb for Class 12 Computer Science Chapter 2 File Handling

Text Files, Binary Files and the open() File Modes

Every file question starts with two choices: is the file text or binary, and what do you want to do with it? A text file stores readable characters, applies an encoding (UTF-8 by default), and translates end-of-line markers. A binary file stores raw bytes with no encoding and no newline translation, which is why pickle files use it.

  • r: read only. The pointer sits at the start and the file must already exist.
  • w: write only. It creates the file if missing and erases all old content the instant it opens.
  • a: append. The pointer sits at the end and old content is kept.
  • + adds the opposite operation (so r+ is read and write); b turns any mode binary (so rb, wb, ab).
Watch Out: The most repeated trap is mixing up r+ and w+. Both allow read and write, but w+ first empties the file while r+ keeps the old content. When the question says "both read and write" without erasing, the answer is r+.

Read each mode requirement as a three-flag checklist: pick the base letter for the action, add + if a second action is asked, and add b if the word "binary" or a .dat extension appears. Run Q 3 through this and the four answers (r+, wb, a+, rb) fall out with no memorisation.

Reading and Writing: read(), readline(), readlines(), write() and writelines()

Once a file is open, the read and write methods move data in and out. The NCERT chapter lists five methods, and the exam tests which one returns what. Keep their return types separate, because that single fact decides most of the marks.

f = open("notes.txt", "r")
line1 = f.readline()      # one line  -> str ("" at end of file)
f.seek(0)
all_lines = f.readlines() # all lines -> list of str ([] at end)
f.seek(0)
whole = f.read()          # whole file -> one str
f.close()

On the write side, write() takes one string and writelines() takes a list of strings. The plural name fools students: writelines() does not add a newline after each item. You must put \n yourself in both cases, exactly as Q 6 needs.

Quick Tip: Read each method name as "single item" versus "list of items". readline/write are single; readlines/writelines are list-based. No method ever inserts a newline for you.

Why You Must Close a File and the Safe with Statement

When you call write(), the data does not go straight to disk. Python keeps it in a memory buffer and copies it to disk only when the buffer fills or the file is closed. That copy is called flushing, and close() is the guaranteed flush.

  • Close to flush: closing forces the final flush so every byte is on disk, and it frees the file handle, a limited operating-system resource.
  • If you forget: buffered data can be lost if the program crashes, and open handles can pile up. On a clean exit Python usually flushes by luck, but that luck is the danger.
  • No error is shown: forgetting close() never raises an error. The failure is silent and appears later as missing or partial data.

The professional fix is the with statement. It hands the file to a context manager that closes it automatically when the block ends, even if an error is raised inside the block. This is exactly the contrast Q 5 asks about.

with open("hello.txt", "r") as f:
    data = f.read()       # whole file into data
# file is closed automatically here, even on an error
Pickling with dump() and load() saving Python objects to a binary file for Class 12 Computer Science

Pickling: Saving Whole Python Objects with dump() and load()

A text file can only store strings, so saving a list of records means writing your own code to flatten and parse it. The pickle module removes that work. Pickling (serialization) turns a whole Python object into a byte stream; unpickling (deserialization) rebuilds the exact object from those bytes.

StepMethodFile mode
Pickling / serialization (object to bytes)pickle.dump(object, file)"wb" (binary write)
Unpickling / deserialization (bytes to object)pickle.load(file)"rb" (binary read)
import pickle
data = [10, 20, 30]
f = open("nums.dat", "wb")     # binary write
pickle.dump(data, f)           # serialize
f.close()

f = open("nums.dat", "rb")     # binary read
back = pickle.load(f)          # deserialize
print(back, type(back))
f.close()
Remember: Pickle works in bytes, so the binary modes "wb" and "rb" are mandatory. Pairing dump() with a plain "w" file, or reading a .dat pickle with read() in text mode, both fail. This is the single most common pickling error.

Common Mistakes Students Make in the File Handling Chapter

The repeat-offender mistakes in File Handling board answers:

  • Forgetting the manual newline: write() and writelines() never add \n, so the lines run together. This is the most common slip in Q 6 and Q 8.
  • Confusing r+ with w+: both read and write, but w+ empties the file first. Part (a) of Q 3 needs the content-preserving r+.
  • Using text modes for pickle: a .dat pickle must use "wb" to write and "rb" to read; "w" or "r" raises an error.
  • Saying "close raises an error if skipped": it does not. Forgetting close() is silent, which is exactly why it is dangerous.
  • Missing the type casts: input() returns a string, so Item No and Qty need int() and Price needs float() before Price * Qty works in Q 10.

How to Use the File Handling NCERT Solutions PDF for Board Prep

File Handling is concept-heavy in the first half and program-heavy in the second. The best approach is two passes: one for the modes and methods, one for writing the programs by hand.

First pass: modes and methods (1 hour)

Read the chapter and make a small table of the file modes and the read and write methods. Write one line of meaning next to each: which mode keeps data, which erases it, which method returns a string and which returns a list. This table answers Q 1, Q 2 and Q 3 directly.

Second pass: write the programs (1.5 to 2 hours)

Hand-write Q 6, Q 7, Q 8 and Q 10 on paper, then open these solutions and check. Pay attention to the manual \n, the correct file mode, and the binary "wb"/"rb" for pickle, because these specifics decide full marks on the program questions.

JEE and CUET angle

For students preparing competitive exams, file handling and serialization appear in CUET Computer Science and in the programming rounds of JEE-level coding tests. The pickle dump and load pattern and the file mode logic here double as competitive prep.

Previous Year Question Trends from the File Handling Chapter

The File Handling chapter is tested in CBSE board papers mainly through file-mode questions, a program on reading or writing a text file, and a pickle binary-file program. The table below maps the asked question types across recent board papers.

YearQuestion type askedMarks
2025State the file mode for a given task; difference between read() and readline()1 + 2
2024Write a program to count lines in a text file; pickle a list to a binary file3 + 3
2023Explain pickling; write a program to append records using a binary file2 + 4
2022Difference between write() and writelines(); read and display a text file2 + 3
2021Why close a file; program to read a binary file and display records2 + 4

Also Check: The full set of CBSE board paper questions for this chapter is included in the downloadable PDF above, updated for the 2026-27 cycle.

Other Resources for Class 12 Computer Science Chapter 2 File Handling in Python

Pair this NCERT Solutions PDF with the matching revision notes, handwritten notes and the official NCERT book chapter. All resources for Class 12 Computer Science Chapter 2 File Handling in Python are linked below.

ResourceWhat it coversOpen
NCERT SolutionsStep-by-step answers to all 10 exercise questions, with an Expert Solution for each.You are here
NotesConcept-first revision notes on text vs binary files, file modes, read and write methods, and pickling.Class 12 Computer Science Chapter 2 Notes
Handwritten NotesScanned-style handwritten pages for last-minute board revision.Class 12 Computer Science Chapter 2 Handwritten Notes
NCERT Book PDFOfficial NCERT Computer Science Chapter 2 File Handling in Python textbook in PDF form.Class 12 Computer Science Chapter 2 NCERT Book PDF

NCERT Solutions for Class 12 Computer Science: All Chapters

Related Links: Use the table below to open the NCERT Solutions for the other chapters of Class 12 Computer Science. Every chapter ships with the same step-by-step answer style, full PDF download, and revision FAQ.

All NCERT Solutions for Class 12 Computer Science Chapter 2 File Handling in Python with Step-by-Step Solutions

Q 1

Differentiate between:
a) text file and binary file
b) readline() and readlines()
c) write() and writelines()

Q 2

Write the use and syntax for the following methods:
a) open()   b) read()   c) seek()   d) dump()

Q 3

Write the file mode that will be used for opening the following files. Also, write the Python statements to open the following files:
a) a text file "example.txt" in both read and write mode
b) a binary file "bfile.dat" in write mode
c) a text file "try.txt" in append and read mode
d) a binary file "btry.dat" in read only mode

Q 4

Why is it advised to close a file after we are done with the read and write operations? What will happen if we do not close it? Will some error message be flashed?

Q 5

What is the difference between the following set of statements (a) and (b)?

a) P = open("practice.txt", "r")
   P.read(10)

b) with open("practice.txt", "r") as P:
       x = P.read()
Q 6

Write a command(s) to write the following lines to the text file named hello.txt. Assume that the file is opened in append mode.
" Welcome my class"
"It is a fun place"
"You will learn and play"

Q 7

Write a Python program to open the file hello.txt used in question no 6 in read mode to display its contents. What will be the difference if the file was opened in write mode instead of append mode?

Q 8

Write a program to accept string/sentences from the user till the user enters "END". Save the data in a text file and then display only those sentences which begin with an uppercase alphabet.

Q 9

Define pickling in Python. Explain serialization and deserialization of Python object.

Q 10

Write a program to enter the following records in a binary file: Item No (integer), Item_Name (string), Qty (integer), Price (float). The number of records to be entered should be accepted from the user. Read the file to display the records in the format: Item No, Item Name, Quantity, Price per item, Amount (calculated as Price × Qty).

NCERT Solutions Class 12 Computer Science Chapter 2 File Handling in Python FAQs

Ques. How many questions are there in NCERT Class 12 Computer Science Chapter 2 File Handling in Python?

Ans. There are 10 end-of-chapter exercise questions in NCERT Class 12 Computer Science Chapter 2 File Handling in Python. All 10 are solved with full answers and an Expert Solution in the PDF. The mix is differentiate questions on files and methods, use-and-syntax questions, a file-mode question, conceptual questions on close() and pickling, and program questions on appending lines, filtering sentences, and reading and writing item records in a binary file.

Ques. What is the difference between a text file and a binary file in Class 12 Computer Science?

Ans. A text file stores data as readable characters and is opened in text mode (r, w, a). Python applies an encoding such as UTF-8 and translates end-of-line markers, so you can open it in a normal editor. A binary file stores data as raw bytes exactly as they sit in memory, is opened in binary mode (rb, wb, ab), applies no encoding and does no newline translation, and looks like garbage in a text editor. Pickle files with a .dat extension are binary files, which is why they must use wb to write and rb to read.

Ques. What is the difference between write() and writelines() in Python?

Ans. The write() method writes one string to the file and returns the number of characters written. The writelines() method writes a list (or any iterable) of strings in one call and returns None. The most important point for the board exam is that neither method adds a newline on its own. The plural name of writelines() fools students into thinking it adds a newline after each list item, but it does not, so you must put a \n inside each string yourself if you want separate lines on disk.

Ques. Why should you close a file in Python, and what happens if you do not?

Ans. You close a file so the data sitting in the memory buffer is flushed to disk and the file handle is released. If you do not close it, the buffered data may never reach the disk if the program crashes, and open handles can pile up until the program cannot open more files. Importantly, forgetting to close a file does not raise any error, so the program seems to work and the loss shows up later as missing or partial data. The safest habit is the with statement, which closes the file automatically when its block ends.

Ques. What is pickling in Python and which file mode does it need?

Ans. Pickling, also called serialization, is converting a whole Python object such as a list or dictionary into a byte stream that can be saved in a binary file. It is done with pickle.dump(object, file) into a file opened in binary write mode "wb". The reverse, unpickling or deserialization, rebuilds the exact original object with pickle.load(file) from a file opened in binary read mode "rb". The binary modes are mandatory because pickle works in bytes, so pairing dump() with a plain "w" file is a common error that fails.

Ques. How many pages is the Class 12 Computer Science File Handling in Python NCERT Solutions PDF?

Ans. The File Handling in Python NCERT Solutions PDF runs about 18 pages and covers all 10 exercise questions with step-by-step Python code, sample runs, comparison tables, and an Expert Solution for each question. Both Normal and HD versions are available from this page, and both are free to download for the 2026-27 session.

Ques. Is the NCERT Solutions for Class 12 Computer Science Chapter 2 aligned with the 2026-27 syllabus?

Ans. Yes. This page reflects the current 2026-27 CBSE syllabus for Class 12 Computer Science. The File Handling in Python chapter is part of the current cycle, and every answer follows the NCERT textbook, including the file modes, the read and write methods, the with statement, and pickling with dump() and load(). The solutions are useful for the CBSE board exam, and the same file-handling ideas help with CUET Computer Science and JEE-level programming.

Ques. What is the difference between append mode and write mode in Python file handling?

Ans. Append mode "a" opens a file with the pointer at the end and keeps all existing content, so new text is added below what is already there. Write mode "w" is destructive: it truncates the file to zero bytes the instant open() runs, even before any write happens, so any earlier content is lost and only the new text remains. Both modes create the file if it does not exist. This is exactly the contrast asked in Question 7, where opening hello.txt in write mode instead of append would have wiped the lines added earlier.