Courses
Courses for Kids
Free study material
Offline Centres
More
Store Icon
Store

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

ffImage
banner

File Handling in Python: Important Questions, Definitions & Solutions

Get exam-ready with the NCERT Solutions for Class 12 Computer Science Chapter 2: File Handling in Python designed for the CBSE 2025–26 syllabus. Here, you’ll find clear, stepwise answers matching your textbook’s flow, perfect for building confidence ahead of board exams.


Solve every important question using detailed, exercise-wise solutions with exam tips, so you understand concepts and ace scoring in File Handling in Python. Boost your preparation with intext, back exercise answers, and quick revision notes—all in one spot.


Download a free PDF, revise definitions and diagrams, and avoid common mistakes with structured content developed by experts. Your journey to scoring full marks in Class 12 Computer Science just got simpler and smarter!


File Handling in Python: Important Questions, Definitions & Solutions

Exercise Solutions: File Handling in Python

1. Differentiate between:


  • (a) text file and binary file
    Answer: A text file contains human-readable characters, with each byte representing a character, and can be opened by any text editor. Its data is stored as ASCII or Unicode values. A binary file contains data as a stream of bytes representing images, audio, video, or executable files, which are not human readable and require specific programs to access. Any bit change in a binary file can corrupt the file.
  • (b) readline() and readlines()
    Answer: The readline() method reads a single complete line from a file, ending with a newline character, and returns it as a string. The readlines() method reads all lines from a file and returns a list of strings, each string representing a line (including the newline character).
  • (c) write() and writelines()
    Answer: The write() method writes a single string to a file and returns the number of characters written. The writelines() method writes a list (or other iterable) of strings to a file, without returning the number of characters written. Newline characters must be added manually to each string in the list for separate lines.

2. Write the use and syntax for the following methods:


  • (a) open()
    Use: The open() method opens a file with a specified name and mode, returning a file object (file handle) for further operations.
    Syntax: file_object = open(file_name, access_mode)
  • (b) read()
    Use: The read() method reads data from the file. If an integer n is specified, it reads n bytes. Otherwise, reads the whole file.
    Syntax: file_object.read(n)
  • (c) seek()
    Use: The seek() method positions the file object at a specified byte position in the file.
    Syntax: file_object.seek(offset [, reference_point])
  • (d) dump()
    Use: The dump() method serializes (pickles) a Python object and writes it to a binary file.
    Syntax: pickle.dump(data_object, file_object)

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
    File Mode: 'r+'
    Python Statement: fh = open("example.txt", "r+")
  • (b) a binary file "bfile.dat" in write mode
    File Mode: 'wb'
    Python Statement: fh = open("bfile.dat", "wb")
  • (c) a text file "try.txt" in append and read mode
    File Mode: 'a+'
    Python Statement: fh = open("try.txt", "a+")
  • (d) a binary file "btry.dat" in read only mode.
    File Mode: 'rb'
    Python Statement: fh = open("btry.dat", "rb")

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?


Answer: It is advised to close a file after read and write operations to free up system resources (like memory) and to ensure that all unwritten or unsaved data is properly written (flushed) to the file. If a file is not closed, Python may still close it automatically when the file object is deleted or when the program ends, but this is not a good practice and could lead to data loss or resource leaks. Generally, no error message will be shown if not closed, but it is best practice to close files explicitly.


5. What is the difference between the following set of statements (a) and (b):


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

    Answer: This opens "practice.txt" in read mode and reads 10 bytes. However, the file must be closed explicitly using P.close(), else it remains open until garbage collected or the program ends.
  • (b)
    with open("practice.txt", "r") as P:
        x = P.read()
    Answer: This opens the file in read mode using the with clause and reads the entire content. The file is closed automatically after the block ends, even if an exception occurs, making it safer and more concise.

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”


Answer:

file = open("hello.txt", "a")
lines = [
    "Welcome my class\n",
    "It is a fun place\n",
    "You will learn and play"
]
file.writelines(lines)
file.close()

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?


Answer:

f = open("hello.txt", "r")
content = f.read()
print(content)
f.close()

If the file was opened in write mode instead of append mode, the existing contents would be overwritten and lost before new lines are written. Append mode adds new lines to the end, preserving previous contents.


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.


Answer:

f = open("new.txt", "w")
while True:
    st = input("Enter next line:")
    if st == "END":
        break
    f.write(st + '\n')
f.close()

f = open("new.txt", "r")
for line in f:
    if line and line[0].isupper():
        print(line, end='')
f.close()

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


Answer: Pickling is the process of converting a Python object into a byte stream for storage in a binary file. Serialization is transforming data or an object in memory to a stream of bytes (pickling), which can be saved or transmitted. Deserialization (unpickling) reverses this process, reconstructing the object from the byte stream.


10. Write a program to enter the following records in a binary file:
Item No           integer
Item_Name    string
Qty                   integer
Price                float

Number of records to be entered should be accepted from the user. Read the file to display the records in the following format:

Item No:
Item Name:
Quantity:
Price per item:
Amount: (to be calculated as Price * Qty)


Answer:

import pickle

with open("item.dat", 'wb') as itemfile:
    n = int(input("How many records to be entered? "))
    for i in range(n):
        ino = int(input("Enter item no: "))
        iname = input("Enter item name: ")
        qty = int(input("Enter quantity: "))
        price = float(input("Enter price: "))
        item = {"Item no": ino, "Item Name": iname, "Qty": qty, "Price": price}
        pickle.dump(item, itemfile)
    print("Successfully written item data")
with open("item.dat", "rb") as file:
    try:
        while True:
            item = pickle.load(file)
            print("\nItem No:", item["Item no"])
            print("Item Name:", item["Item Name"])
            print("Quantity:", item["Qty"])
            print("Price per item:", item["Price"])
            print("Amount:", item["Qty"] * item["Price"])
    except EOFError:
        pass

Learn File Handling in Python: Key Concepts for Class 12

A strong grasp of Python file handling is essential for students of Class 12 Computer Science. This chapter covers types of files, reading and writing operations, and the Pickle module, building the foundation for real-world programming and exam readiness.


Using these NCERT solutions for the 2025-26 syllabus, you can easily understand text and binary files, access modes, and file operations. Practicing exercises will help improve your coding skills and performance in board exams.


Consistent practice of exercise-based questions and reviewing key programs will ensure better conceptual clarity. Focus on the practical aspects discussed in the chapter to boost your exam score effectively.


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

1. What is File Handling in Python according to Class 12 Computer Science NCERT syllabus?

File Handling in Python involves working with files to read, write, and manipulate data efficiently. It is a key topic in Class 12 Computer Science Chapter 2 for the CBSE 2025–26 syllabus.

Main aspects covered include:

  • Opening and closing files using functions like open() and close()
  • Reading from and writing to files (text and binary modes)
  • Using file modes such as ‘r’, ‘w’, ‘a’
  • Handling file exceptions and errors
  • File pointer operations and methods like read(), readline(), write()
Understanding these skills will help you attempt both theory and practical questions successfully in board exams.

2. How can I write stepwise NCERT answers for File Handling in Python Class 12 to score full marks?

To score full marks in CBSE exams, follow these tips when writing stepwise answers for File Handling in Python Class 12:

  • Start with a precise definition of the topic or process.
  • Use clear headings for each step (e.g., Step 1: Open the File).
  • Explain each function/method and provide Python code snippets where required.
  • Highlight key terms (open, read, write, close).
  • End with a conclusion or output sample if applicable.
  • Maintain proper indentation and neat formatting.
Stepwise structure helps examiners grant step marks as per the marking scheme.

3. Where can I download the NCERT Solutions PDF for Class 12 Computer Science Chapter 2 File Handling in Python?

You can download the chapterwise NCERT Solutions PDF for Class 12 Computer Science Chapter 2 File Handling in Python from trusted academic websites and educational portals.

Steps to download:

  • Visit the official solution page for the chapter.
  • Search for a 'Free PDF Download' or 'Download PDF' button.
  • Click to download for offline study and revision.
Having the free PDF ensures you can revise stepwise solutions without being online.

4. Which important questions are likely to appear from the File Handling in Python chapter in Class 12 exams?

Key questions from File Handling in Python Class 12 often include both theory and practical-based formats:

Common exam questions:

  • Define file handling and explain its importance.
  • Differentiate between text and binary files.
  • Write Python code to read/write files.
  • Explain file modes ('r', 'w', 'a').
  • Short notes on file methods (read(), write(), readline()).
  • Error handling with file operations.
Practicing NCERT and exemplar questions will cover most likely exam queries.

5. Are diagrams or definitions mandatory in File Handling in Python answers for Class 12 CBSE exams?

Yes, including clear definitions and well-labelled diagrams (if applicable) can help secure step marks in CBSE Computer Science exams.

When to use:

  • Always begin long answers with a definition.
  • Incorporate flowcharts or schematic representations when explaining file operations.
  • Highlight key terms using bold or underlining in your answer sheet.
Structured answers with definitions and neat diagrams align with CBSE marking guidelines.

6. How should I structure long answers on File Handling in Python Class 12 for higher marks?

For long answer questions on File Handling in Python:

  • Start with a definition of the main concept.
  • Break down the answer into logical steps or headings.
  • Include diagrams/flowcharts where appropriate.
  • Explain file modes, methods, and operations with examples.
  • Summarize with a conclusion highlighting importance or applications.
Clarity, bullet points, and sequence help meet CBSE’s step mark criteria.

7. What are the main topics covered in NCERT Solutions for Class 12 Computer Science Chapter 2 File Handling in Python?

The NCERT Solutions for Class 12 Computer Science Chapter 2 cover:

  • Introduction to file handling in Python
  • Types of files – text vs binary
  • Opening, reading, writing, and closing files
  • File modes: 'r', 'w', 'a', 'r+', etc.
  • File methods: read(), readline(), write(), writelines()
  • Error/exception handling in file operations
  • Practical exercises and application-based questions
Mastering these ensures strong performance in theory and practical exams.

8. Are NCERT Solutions enough for Class 12 Computer Science exams?

NCERT Solutions provide comprehensive coverage for Class 12 Computer Science board exams, especially for understanding concepts, definitions, and stepwise answers.

For best results:

  • Revise all NCERT back exercises and intext questions.
  • Practice with exemplar problems and sample papers.
  • Refer to additional important questions for extra practice.
This approach aligns your preparation with CBSE marking schemes.

9. Do examiners award partial marks for correct steps even if the final answer is wrong?

Yes, CBSE examiners commonly award partial (step) marks if your approach, logic, or intermediate steps are correct, even if the final answer has an error.

  • Show all logical steps clearly.
  • Use correct syntax and terminology.
  • Highlight your methodology.
This is especially important in Python programming solutions and theoretical explanations.

10. What are the most common mistakes to avoid in File Handling in Python Class 12 answers?

Avoiding frequent mistakes ensures you don’t lose easy marks in File Handling in Python Class 12:

  • Missing file closure after operations with close()
  • Incorrect file modes ('r', 'w', etc.)
  • Not handling exceptions in file operations
  • Unclear or poorly written Python code
  • Missing definitions, steps, or diagrams
Careful answer structuring and practice can help you avoid these errors.

11. How can I revise File Handling in Python Class 12 quickly before exams?

To revise File Handling in Python Class 12 efficiently:

  • Go through NCERT solutions and quick notes.
  • Practice writing key definitions and syntax for file methods.
  • Attempt sample questions and previous year problems.
  • Use chapterwise revision planners (e.g., 1-day, 3-day plans).
Structured revision helps you recall important points in the exam.

12. What is the marking scheme for File Handling in Python Class 12 Computer Science in CBSE exams?

The CBSE marking scheme for File Handling in Python Class 12 awards:

  • Step marks for each correct step or explanation
  • Marks for accurate definitions, diagrams, and neat presentation
  • Special weight for code structure and logical flow
  • Partial credit for correct approach, even with minor errors
Following the NCERT answer structure will help maximize your score.