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
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
bto the mode (e.g.,rb,wb,ab+).
3. Text File Methods
A. Reading
read(n): Readsnbytes. Ifnis empty, reads the whole file. Returns a String.readline(): Reads a single line (up to\n). Returns a String.readlines(): Reads all lines. Returns a List of Strings.
B. Writing
write(str): Writes a string to the file.writelines(list): Writes a list of strings. Note: Does not add\nautomatically.
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)
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.
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.
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
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)
tell(): Returns current cursor position (Integer).seek(offset, whence): Moves cursor.Offset: Number of bytes to move.
Whence (Reference point):
0: Beginning (Default).1: Current Position (Binaryrb/wbonly).2: End of File (Binaryrb/wbonly).
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.
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.
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.
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
Post a Comment