Chapter 02 - File Handling

CBSE Class 12 Computer Science

2.1 Introduction to Files

Why Do We Need Files?

Till now, programs:

  • Take input from keyboard
  • Show output on screen
  • Lose data once program ends

👉 Files are needed to store data permanently on secondary storage (HDD, SSD, pen drive).

Definition of File

A file is a named location on secondary storage used to store data permanently.

📌 Python programs themselves are stored as files with .py extension.

Real-Life Examples

  • Employee records
  • Student databases
  • Inventory systems
  • Log files

2.2 Types of Files

Python mainly deals with two types of files:


🔸 2.2.1 Text Files

Text files contain human-readable characters.

📌 Examples:

  • .txt
  • .py
  • .csv

Characteristics

  • Stored as ASCII / Unicode characters
  • Can be opened in Notepad, VS Code
  • Each line ends with newline character \n

Example

Hello Python
Welcome to File Handling

📌 Internally stored as binary (0s and 1s) but displayed as readable text.


🔸 2.2.2 Binary Files

Binary files contain non-human-readable data.

📌 Examples:

  • .jpg
  • .mp3
  • .mp4
  • .exe
  • .dat

Characteristics

  • Opened using specific programs
  • Even a single-bit change can corrupt the file
  • Used for images, videos, objects

2.3 Opening and Closing a Text File


🔸 Opening a File

Python uses the open() function.

Syntax

file_object = open(file_name, mode)

📌 file_object → file handle 📌 mode → how the file is accessed


🔸 File Opening Modes (Very Important)

Mode Meaning
r Read (default)
w Write (overwrites file)
a Append
r+ Read + Write
a+ Append + Read
b Binary mode

Example

f = open("data.txt", "r")

🔸 Closing a File

Always close a file to:

  • Save data
  • Free memory

Syntax

f.close()

📌 Python flushes buffered data before closing.


🔸 Using with Statement (BEST PRACTICE)

Automatically closes the file.

with open("data.txt", "r") as f:
    content = f.read()

✔ No need for close() ✔ Safe even if exception occurs


2.4 Writing to a Text File

To write data, file must be opened in:

  • w (write)
  • a (append)

🔸 write() Method

Writes a single string.

f = open("sample.txt", "w")
f.write("Welcome to Python\n")
f.write("File Handling Chapter")
f.close()

📌 Returns number of characters written.


🔸 writelines() Method

Writes multiple strings.

lines = ["Apple\n", "Banana\n", "Mango\n"]
f = open("fruits.txt", "w")
f.writelines(lines)
f.close()

📌 No automatic newline → must add \n


2.5 Reading from a Text File


🔸 read() Method

Reads entire file.

f = open("sample.txt", "r")
data = f.read()
print(data)
f.close()

🔸 read(n) Method

Reads n characters.

print(f.read(10))

🔸 readline() Method

Reads one line at a time.

f = open("sample.txt")
print(f.readline())
print(f.readline())
f.close()

🔸 readlines() Method

Reads all lines as a list.

f = open("sample.txt")
lines = f.readlines()
print(lines)
f.close()

2.6 Setting Offsets in a File

File pointer determines current position.


🔸 tell() Method

Returns current position.

f = open("sample.txt")
print(f.tell())

🔸 seek() Method

Moves file pointer.

f.seek(0)     # Beginning
f.seek(5)     # Move to 5th byte

📌 Syntax:

f.seek(offset, reference)
Reference Meaning
0 Beginning
1 Current position
2 End of file

2.7 Creating and Traversing a Text File


🔸 Creating a File

Opening in w or a creates file automatically.

f = open("newfile.txt", "w")
f.write("File created successfully")
f.close()

🔸 Traversing a File (Line by Line)

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

✔ Most efficient method ✔ Exam-favourite program


2.8 The Pickle Module

Used for binary file handling.


🔸 Why Pickle?

  • Stores Python objects directly
  • Faster than text files
  • Used for lists, dictionaries, custom objects

🔸 Writing Data using Pickle

import pickle

data = ["Python", "Java", "C++"]

f = open("lang.dat", "wb")
pickle.dump(data, f)
f.close()

🔸 Reading Data using Pickle

import pickle

f = open("lang.dat", "rb")
data = pickle.load(f)
print(data)
f.close()

📌 File must be opened in binary mode (wb, rb)


📝 NCERT EXAM SUMMARY (Must Remember)

  • Files provide permanent storage
  • Text files → human readable
  • Binary files → machine readable
  • with statement → safest way
  • write()writelines()
  • seek() controls pointer
  • pickle → object serialization

Board-Level Solved Programs (Chapter 2)


Program 1: Create and Write to a Text File

f = open("data.txt", "w")
f.write("Welcome to File Handling\n")
f.write("CBSE Class 12 Computer Science")
f.close()

📌 Concept: File creation, write()


Program 2: Read Entire File Using read()

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

📌 Concept: read()


Program 3: Read File Line by Line (readline())

f = open("data.txt", "r")
print(f.readline())
print(f.readline())
f.close()

📌 Concept: readline()


Program 4: Read All Lines Using readlines()

f = open("data.txt", "r")
lines = f.readlines()
print(lines)
f.close()

📌 Concept: List of lines


Program 5: Append Data to an Existing File

f = open("data.txt", "a")
f.write("\nThis line is appended")
f.close()

📌 Concept: Append mode (a)


Program 6: Write Multiple Lines Using writelines()

lines = ["Python\n", "Java\n", "C++\n"]
f = open("languages.txt", "w")
f.writelines(lines)
f.close()

📌 Note: No automatic newline


Program 7: Count Number of Lines in a File

f = open("data.txt", "r")
count = 0
for line in f:
    count += 1
f.close()
print("Number of lines:", count)

📌 Very common exam program


Program 8: Count Words in a File

f = open("data.txt", "r")
words = 0
for line in f:
    words += len(line.split())
f.close()
print("Number of words:", words)

Program 9: Count Characters in a File

f = open("data.txt", "r")
text = f.read()
f.close()
print("Characters:", len(text))

Program 10: Search a Word in a File

f = open("data.txt", "r")
word = "Python"
found = False

for line in f:
    if word in line:
        found = True
        break

f.close()

if found:
    print("Word found")
else:
    print("Word not found")

Program 11: Copy Contents from One File to Another

f1 = open("data.txt", "r")
f2 = open("copy.txt", "w")

f2.write(f1.read())

f1.close()
f2.close()

📌 Classic CBSE program


Program 12: Read File Using with Statement

with open("data.txt", "r") as f:
    print(f.read())

📌 Best practice


Program 13: Display Lines Starting with a Vowel

f = open("data.txt", "r")
for line in f:
    if line[0].lower() in "aeiou":
        print(line, end="")
f.close()

Program 14: Use of tell()

f = open("data.txt", "r")
print(f.tell())
f.read(10)
print(f.tell())
f.close()

📌 Concept: File pointer position


Program 15: Use of seek()

f = open("data.txt", "r")
f.seek(5)
print(f.read())
f.close()

Program 16: Handle File Not Found Exception

try:
    f = open("abc.txt", "r")
    print(f.read())
except FileNotFoundError:
    print("File does not exist")

📌 Links Chapter 1 + 2


Program 17: Store List Using Pickle

import pickle

data = [10, 20, 30, 40]
f = open("numbers.dat", "wb")
pickle.dump(data, f)
f.close()

📌 Binary file


Program 18: Read List from Pickle File

import pickle

f = open("numbers.dat", "rb")
data = pickle.load(f)
f.close()
print(data)

Program 19: Store Dictionary Using Pickle

import pickle

student = {"Roll": 1, "Name": "Amit", "Marks": 92}
f = open("student.dat", "wb")
pickle.dump(student, f)
f.close()

Program 20: Read Dictionary from Pickle File

import pickle

f = open("student.dat", "rb")
student = pickle.load(f)
f.close()
print(student)

CBSE 2025 CASE-STUDY QUESTIONS (Chapter 2)

Case Study 1: School Record System

A school stores student records in a text file.

Questions:

  1. Which file mode is used to add new records without deleting old data? ✔ a

  2. Write a program to count total students stored in the file.

    f = open("students.txt", "r")
    count = 0
    for line in f:
    count += 1
    f.close()
    print("Total students:", count)
    

Case Study 2: Library Management System

Library books are stored in a file books.txt.

  1. How will you check if a book exists?

    f = open("books.txt", "r")
    book = input("Enter book name: ")
    found = False
    
    for line in f:
    if book in line:
        found = True
        break
    
    f.close()
    
    if found:
    print("Book available")
    else:
    print("Book not available")
    

Case Study 3: Log File Analysis

A log file records user activities.

  1. Which method reads the file line by line efficiently? ✔ for line in file

  2. Why is with preferred?

✔ Automatically closes file, prevents data loss.


Case Study 4: Student Result Processing

Student marks are stored using pickle.

  1. Why use pickle instead of text file?

✔ Stores Python objects directly ✔ Faster and safer

  1. Write code to read the stored object.

    import pickle
    f = open("result.dat", "rb")
    data = pickle.load(f)
    f.close()
    print(data)
    

Case Study 5: Data Security Scenario

Old hard disks are discarded without deleting files properly.

  1. What is the risk? ✔ Data recovery by unauthorized users

  2. How can this be prevented? ✔ Proper data deletion / shredding tools