Ultimate Last-Minute Revision Notes for Unit I: File Handling (Computer Science Class 12)

 Here are the Ultimate Last-Minute Revision Notes for Unit I: File Handling (Computer Science Class 12). This unit typically holds 10-15 Marks and is critical for the practical exam as well.


1. Concept: Types of Files

FeatureText File (.txt, .py, .csv)Binary File (.dat, .jpg, .mp3)
StorageStores information in ASCII or Unicode characters.Stores information in raw bytes (same as memory).
ReadabilityHuman-readable.Not human-readable (looks like garbage text).
TranslationEOL Translation: Converts \n to OS-specific newline.No Translation: Faster and more efficient.

2. File Modes (The open() function)

Syntax: file_obj = open("filename", "mode")

Cheat Sheet for Modes:

  • r: Read only. Default mode. File must exist (else Error). Pointer at Beginning.

  • w: Write only. Creates file if not exists. Overwrites (truncates) if exists. Pointer at Beginning.

  • a: Append. Creates file if not exists. Adds to end. Pointer at End.

  • r+: Read & Write. File must exist. Pointer at Beginning.

  • w+: Write & Read. Overwrites file. Pointer at Beginning.

  • a+: Append & Read. Pointer at End.

Note: For Binary files, add b to the mode (e.g., rb, wb, ab+).


3. Text File Methods

A. Reading

  1. read(n): Reads n bytes. If n is empty, reads the whole file. Returns a String.

  2. readline(): Reads a single line (up to \n). Returns a String.

  3. readlines(): Reads all lines. Returns a List of Strings.

B. Writing

  1. write(str): Writes a string to the file.

  2. writelines(list): Writes a list of strings. Note: Does not add \n automatically.

The with Statement (Best Practice)

Automatically closes the file, even if an error occurs.

with open("data.txt", "r") as f:
    print(f.read())
# No f.close() needed here

4. Binary Files (pickle Module)

Used for Serialization (converting Python objects like Lists/Dictionaries to byte stream).

Import: import pickle

A. Writing (dump)

Python
import pickle
data = [10, "Ali", 95.5]
with open("student.dat", "wb") as f:
    pickle.dump(data, f)  # Syntax: dump(object, file_handle)

B. Reading (load)

Crucial: You must use a try-except block to catch EOFError (End of File Error) because binary files don't have a specific EOF marker like text files.

Python
import pickle
with open("student.dat", "rb") as f:
    try:
        while True:
            rec = pickle.load(f)  # Syntax: load(file_handle)
            print(rec)
    except EOFError:
        pass 

5. CSV Files (csv Module)

Import: import csv

A. Writing

Crucial: Use newline='' in open() to prevent empty lines between rows in Windows.

Python
import csv
with open("data.csv", "w", newline='') as f:
    wo = csv.writer(f)
    wo.writerow(["Roll", "Name"])       # Write Header
    wo.writerow([1, "Amit"])            # Write Single Row
    wo.writerows([[2, "Bob"], [3, "C"]]) # Write Multiple Rows

B. Reading

Python
import csv
with open("data.csv", "r") as f:
    ro = csv.reader(f)
    for row in ro:
        print(row)  # 'row' is a List of Strings e.g., ['1', 'Amit']

6. File Pointers (Random Access)

  1. tell(): Returns current cursor position (Integer).

  2. seek(offset, whence): Moves cursor.

    • Offset: Number of bytes to move.

    • Whence (Reference point):

      • 0: Beginning (Default).

      • 1: Current Position (Binary rb/wb only).

      • 2: End of File (Binary rb/wb only).

Example: f.seek(-10, 2) moves 10 bytes backwards from the end of a binary file.


7. "Golden Code" (Memorize these Patterns)

Scenario A: Count words starting with 'T' in a Text File.

Python
def count_T():
    c = 0
    f = open("story.txt", "r")
    data = f.read()      # Read whole file
    words = data.split() # Split into list of words
    for w in words:
        if w[0].upper() == 'T':
            c += 1
    print(c)
    f.close()

Scenario B: Search for a record in Binary File.

Python
import pickle
def search(roll_no):
    f = open("student.dat", "rb")
    found = False
    try:
        while True:
            s = pickle.load(f) # s is like {'roll':1, 'name':'A'}
            if s['roll'] == roll_no:
                print("Found:", s)
                found = True
    except EOFError:
        if not found: print("Not Found")
    f.close()

Scenario C: Update a record in Binary File. Logic: Read all records into a list Modify the specific record in the list Truncate file (mode 'wb') and dump the whole list back.

Python
import pickle
def update_marks(roll, new_marks):
    # 1. Read all data
    f = open("student.dat", "rb")
    all_data = []
    try:
        while True:
            all_data.append(pickle.load(f))
    except EOFError:
        f.close()

    # 2. Modify data in memory
    for s in all_data:
        if s['roll'] == roll:
            s['marks'] = new_marks
    
    # 3. Write back to file
    f = open("student.dat", "wb")
    for s in all_data:
        pickle.dump(s, f)
    f.close()

Comments

Popular Posts