Chapter 4: Data File Handling Class 12 Computer Science NCERT Solutions

Chapter 4 – Data File Handling introduces students to the concept of storing and managing data in external files using Python. This chapter is essential for understanding how data can be preserved between program executions. It focuses on file operations such as reading, writing, and appending text and binary files, and highlights the importance of file handling in real-world applications.

What You Will Learn in Chapter 4 – Data File Handling

This chapter helps students understand how to work with data stored in files, rather than relying only on temporary memory (RAM). You will learn how to perform essential file operations, differentiate between text and binary files, and apply file handling in practical programming scenarios.

Key Topics Covered

Introduction to File Handling

  • A file is a named location on disk to store related data.
  • Python provides built-in functions to create, read, write, and append data to files.

Types of Files

  • Text Files: Store data in readable formats using characters (e.g., .txt).
  • Binary Files: Store data in binary format (e.g., images, compiled programs).

File Operations

  • Opening a File: Using the open() function with appropriate mode (\'r\', \'w\', \'a\', \'rb\', \'wb\', etc.)
  • Reading from a File: Using read(), readline(), or readlines()
  • Writing to a File: Using write() or writelines()
  • Appending Data: Using \'a\' mode to add new data at the end of a file
  • Closing a File: Always use file.close() to save resources and avoid data corruption

Working with Text Files

  • Reading entire content or line by line
  • Writing and appending strings to a file
  • Processing lines and words in text

💾 Working with Binary Files

  • Using pickle module to store and retrieve Python objects
  • Functions: pickle.dump(), pickle.load()

Exception Handling with Files

  • Using try-except blocks to handle file-related errors such as file not found, permission errors, etc.

Download Chapter 4 Solutions PDF – Data File Handling

Download a free PDF that includes:

  • All solved NCERT intext and exercise questions
  • Easy-to-understand definitions and key concepts
  • Code snippets with expected output
  • Exam-oriented short and long answers
  • Summary notes for quick revision

Highlights of Our NCERT Solutions

  • Clean, Beginner-Friendly Code with comments
  • Stepwise Explanations for each file handling concept
  • Sample Outputs for clarity
  • Visual Aids: Flowcharts and diagrams for better understanding
  • Practice Programs to boost confidence

Preparation Tips

  • Practice writing programs using text and binary files.
  • Understand modes like \'r\', \'w\', \'a\', \'rb\', and \'wb\'.
  • Focus on real-life applications like reading/writing student records.
  • Use with statement and exception handling consistently.
  • Try programs that count words, lines, and characters from files.

Additional Study Resources

  • Flashcards for file modes and file methods
  • Flowcharts for file handling processes
  • CBSE Previous Year Questions on File Handling
  • Online Quizzes & Mock Papers

Mastering Chapter 4 – Data File Handling

Mastering this chapter will enable you to handle data persistently, a crucial skill for real-world software development and board exams. Whether you\’re creating a simple text editor or working on large data logs, this knowledge is foundational for future programming challenges.

Perfectly aligned for CBSE Class 12 Board Exam and competitive exams like CUET, this chapter paves the way for working with databases and file-based storage systems.

Class 12 Computer Science (Python) – Chapter 4: Data File Handling

NCERT Textbook Questions Solved – Class 12 Computer Science (Python)

Question 1: What is File Handling?

File handling refers to the process of reading from and writing to files. Files are used to store data permanently. In Python, file handling is managed using built-in functions that allow you to interact with files by opening, reading, writing, and closing them.

Question 2: What are the different modes of file handling in Python?

The following modes are available for opening a file in Python:

  • r – Read mode: Opens the file for reading. If the file does not exist, an error is raised.
  • w – Write mode: Opens the file for writing. If the file already exists, it will be overwritten.
  • a – Append mode: Opens the file for appending data to the end of the file. Creates a new file if it doesn’t exist.
  • b – Binary mode: Used for binary files (e.g., images, audio files).
  • x – Exclusive creation mode: Creates a new file, raises an error if file already exists.
  • r+ – Read and write mode: Opens file for both reading and writing.
  • w+ – Write and read mode: Opens file for writing and reading, overwrites file if it exists.
  • a+ – Append and read mode: Opens file for appending and reading.

Question 3: Write a Python program to read the contents of a text file.


# Python program to read the contents of a file
file = open("sample.txt", "r")
content = file.read()
print(content)
file.close()

Explanation: Opens sample.txt in read mode, reads the content, displays it, and then closes the file.

Question 4: Write a Python program to write data to a text file.


# Python program to write data to a file
file = open("sample.txt", "w")
file.write("This is a sample text written to the file.")
file.close()

Explanation: Opens sample.txt in write mode, writes the string to the file, and closes it.

Question 5: What is the use of the with statement in file handling?

The with statement automatically handles opening and closing of files, ensuring the file is closed even if errors occur.


# Demonstrate file handling using with statement
with open("sample.txt", "r") as file:
    content = file.read()
    print(content)

Explanation: No need to manually call close(), it’s handled automatically.

Question 6: Write a Python program to append data to an existing file.


# Append data to an existing file
file = open("sample.txt", "a")
file.write("\nAppended data to the file.")
file.close()

Explanation: Opens sample.txt in append mode, adds new text, and closes the file.

Question 7: How can you read a file line by line in Python?

Using readline():

file = open("sample.txt", "r")
line = file.readline()
while line:
    print(line, end='')
    line = file.readline()
file.close()
Using for loop:

file = open("sample.txt", "r")
for line in file:
    print(line, end='')
file.close()

Explanation: Read lines one at a time using readline() or loop through file object directly.

Question 8: Write a Python program to count the number of lines in a file.


# Count the number of lines in a file
file = open("sample.txt", "r")
line_count = 0
for line in file:
    line_count += 1
print(f"Number of lines in the file: {line_count}")
file.close()

Explanation: Reads each line and increments a counter to count total lines.

Question 9: What is the difference between read() and readlines()?

  • read(): Reads entire content of the file as a single string.
  • readlines(): Reads the file line by line into a list of strings.
Example:

# Using read()
file = open("sample.txt", "r")
content = file.read()
print(content)
file.close()

# Using readlines()
file = open("sample.txt", "r")
lines = file.readlines()
print(lines)
file.close()

Question 10: How can you handle exceptions in file handling?


# Handle exceptions during file handling
try:
    file = open("sample.txt", "r")
    content = file.read()
    print(content)
except FileNotFoundError:
    print("Error: The file does not exist.")
finally:
    file.close()

Explanation: If file not found, catches FileNotFoundError. The file is closed in the finally block.