Class XII · Chapter 2Unit 1, Computational Thinking and Programming, 2 (40 marks)8 min read
Share:WhatsAppLinkedIn

Chapter 2: File Handling in Python

CBSE Unit: Unit 1, Computational Thinking and Programming, 2 (40 marks) Marks Weightage: ~12-15 marks (HIGHEST weightage chapter in the entire exam) Priority: CRITICAL, most programs asked from this chapter


Key Concepts

2.1 What is a File?

  • A named location on secondary storage where data is permanently stored, Variables lose data when program ends; files persist data, Two main types: Text files and Binary files

2.2 Types of Files

Feature Text File Binary File
Content Human-readable characters Non-human readable bytes
Extensions .txt, .py, .csv, .html .dat, .jpg, .mp3, .exe
Storage ASCII/Unicode values of characters Actual content as bytes
EOL Each line terminated by \n No line terminator concept
Readability Can open in any text editor Need specific software
Separators Whitespace, comma, tab Not applicable

2.3 Opening a File

file_object = open(file_name, access_mode)
  • Returns a file handle (file object), If file doesn't exist in write/append mode → creates new file, If file doesn't exist in read mode → raises error

File object attributes:

  • file.closed → True if file is closed
  • file.mode → access mode used
  • file.name → name of the file

File Access Modes (MUST MEMORIZE)

Mode Description File Pointer Creates new? Overwrites?
r Read only Beginning No (error if missing) No
rb Read binary Beginning No No
r+ Read + Write Beginning No No
w Write only Beginning Yes YES, erases all
wb+ Write + Read binary Beginning Yes YES
a Append End Yes No, adds at end
a+ Append + Read End Yes No

Critical difference: w mode DESTROYS existing content. a mode PRESERVES it.

2.4 Closing a File

file_object.close()
  • Frees memory, flushes buffer to disk, Always close files after use, Re-assigning file object auto-closes previous file

2.5 Opening with with clause (RECOMMENDED)

with open("myfile.txt", "r+") as myObject:
    content = myObject.read()
# File automatically closed here -  no need for close()

Advantage: Auto-closes even if exception occurs. Simpler syntax.


Writing to Text Files

write() method

file_object.write(string)
  • Writes a single string, Returns number of characters written, Must add \n manually for new lines, Numeric data must be converted to string first: write(str(marks))
f = open("myfile.txt", "w")
f.write("Hello World\n")    # Returns 12
f.write(str(58))             # Returns 2 (writes "58")
f.close()

writelines() method

file_object.writelines(list_of_strings)
  • Writes multiple strings from a list/tuple, Does NOT add \n automatically, Does NOT return character count
lines = ["Hello everyone\n", "Writing multiline\n", "Third line"]
f = open("myfile.txt", "w")
f.writelines(lines)
f.close()

Reading from Text Files

read([n]) method

content = file_object.read(n)    # reads n bytes
content = file_object.read()     # reads ENTIRE file

readline([n]) method

line = file_object.readline()    # reads ONE complete line (including \n)
partial = file_object.readline(10)  # reads max 10 chars or till \n
  • Returns empty string at EOF, Use in loop to read file line by line

readlines() method

lines = file_object.readlines()  # returns LIST of all lines
# ['Hello everyone\n', 'Writing multiline\n', 'Third line']

Reading with loop (most common)

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

split() vs splitlines()

# split() -  splits a line into words
"Hello World".split()  # ['Hello', 'World']

# splitlines() -  keeps the line as one element
"Hello World".splitlines()  # ['Hello World']

Setting Offsets: tell() and seek()

tell()

position = file_object.tell()  # returns current byte position from beginning

seek(offset, reference_point)

file_object.seek(offset, reference_point)
  • reference_point: 0 = beginning (default), 1 = current, 2 = end
  • offset: number of bytes to move
f = open("testfile.txt", "r+")
f.read()
print(f.tell())    # position at end
f.seek(0)          # go back to beginning
f.seek(10)         # go to 10th byte from beginning

Note: For text files, only seek(0) and seek(0, 0) (beginning) work reliably. Arbitrary seeking works in binary mode.


Binary Files with Pickle Module

What is Pickling?

  • Serialization (pickling): converting Python object → byte stream for storage
  • Deserialization (unpickling): converting byte stream → Python object
  • import pickle is required

dump(), write object to binary file

import pickle
pickle.dump(data_object, file_object)
import pickle
data = [1, "Geetika", 'F', 26]
f = open("mybinary.dat", "wb")
pickle.dump(data, f)
f.close()

load(), read object from binary file

import pickle
store_object = pickle.load(file_object)
import pickle
f = open("mybinary.dat", "rb")
data = pickle.load(f)
f.close()
print(data)  # [1, 'Geetika', 'F', 26]

Reading ALL records from binary file (handle EOFError)

import pickle
try:
    with open("empfile.dat", "rb") as f:
        while True:
            record = pickle.load(f)
            print(record)
except EOFError:
    pass

Critical: Always use try-except EOFError when reading binary files in a loop.


CSV Files (from CBSE syllabus, brief in NCERT)

import csv

# Writing
with open("data.csv", "w", newline='') as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Age"])       # single row
    writer.writerows([["A", 1], ["B", 2]]) # multiple rows

# Reading
with open("data.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

Important Programs for Board Exam

Program 1: Write and read text file

f = open("testfile.txt", "w")
sentence = input("Enter text: ")
f.write(sentence)
f.close()

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

Program 2: Read text file, display words separated by

f = open("story.txt", "r")
for line in f:
    words = line.split()
    for w in words:
        print(w + "#", end="")
    print()
f.close()

Program 3: Count vowels/consonants/upper/lower in file

f = open("story.txt", "r")
v = c = u = l = 0
data = f.read()
for ch in data:
    if ch.isalpha():
        if ch.lower() in 'aeiou':
            v += 1
        else:
            c += 1
        if ch.isupper():
            u += 1
        else:
            l += 1
f.close()
print(f"Vowels: {v}, Consonants: {c}, Upper: {u}, Lower: {l}")

Program 4: Binary file, write and search student records

import pickle

# Write
f = open("students.dat", "wb")
while True:
    roll = int(input("Roll: "))
    name = input("Name: ")
    pickle.dump([roll, name], f)
    if input("More? (y/n): ") == 'n':
        break
f.close()

# Search
f = open("students.dat", "rb")
search = int(input("Enter roll to search: "))
found = False
try:
    while True:
        rec = pickle.load(f)
        if rec[0] == search:
            print("Found:", rec[1])
            found = True
except EOFError:
    pass
if not found:
    print("Record not found")
f.close()

Program 5: Binary file, update marks

import pickle

f = open("students.dat", "rb")
records = []
try:
    while True:
        records.append(pickle.load(f))
except EOFError:
    pass
f.close()

roll = int(input("Enter roll to update: "))
for rec in records:
    if rec[0] == roll:
        rec[2] = int(input("Enter new marks: "))

f = open("students.dat", "wb")
for rec in records:
    pickle.dump(rec, f)
f.close()

Common Board Exam Question Patterns

  1. MCQ: What is the output of read()/readline()? (1 mark)
  2. MCQ: Which mode opens file at end/beginning? (1 mark)
  3. MCQ: Difference between w and a mode? (1 mark)
  4. Short answer: Differentiate text file vs binary file (2 marks)
  5. Short answer: Differentiate read/readline/readlines (2 marks)
  6. Short answer: Differentiate write vs writelines (2 marks)
  7. Program: Read text file, count/search/display (3-4 marks)
  8. Program: Binary file, write/search/update/delete records (4-5 marks)
  9. Program: CSV file, create and read (3 marks)
  10. Explain: Pickling and unpickling (2-3 marks)

Key Points Students Miss

  1. write() does NOT add \n - you must add it manually
  2. writelines() does NOT add \n between strings
  3. w mode DESTROYS existing file content, most common mistake
  4. read() with no argument reads ENTIRE file, file pointer moves to end
  5. After read(), must seek(0) to read again from beginning
  6. Binary file reading MUST use try-except EOFError - no other way to detect end
  7. with clause auto-closes file, no need for close()
  8. \n counts as ONE character in length calculations
  9. readline() includes \n in the returned string
  10. pickle.dump() needs wb mode, pickle.load() needs rb mode

Test Your Knowledge

Take a quick quiz on this chapter

Start Quiz →

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube