Chapter Notes – CBSE Class 12 Computer Science: File Handling in Python
1. Types of Files:
• Text Files: Contain human-readable characters (e.g., .txt, .csv)
• Binary Files: Contain non-readable binary data (e.g., .dat, .bin)
2. Opening and Closing Files:
• open(filename, mode) is used to open a file.
• Modes: 'r' (read), 'w' (write), 'a' (append), 'rb', 'wb', etc.
• file.close() is used to close the file and free up system resources.
3. Reading and Writing Text Files:
• read() , readline() , readlines() → Reading methods
• write() , writelines() → Writing methods
• Use loops for line-by-line reading/writing
Example:
f = open("sample.txt", "r")
for line in f:
print(line)
f.close()
4. File Handling with `` Statement:
• Automatically handles closing
with open("data.txt", "w") as f:
f.write("Hello World")
5. Binary File Handling:
• Use rb and wb modes
• Store non-text data (e.g., images, objects via pickling)
import pickle
with open("data.dat", "wb") as f:
pickle.dump(my_dict, f)
1
6. File Pointer Operations:
• seek(offset) – Moves pointer to specific byte position
• tell() – Returns current file pointer position
7. CSV File Handling (Optional):
• Python provides csv module
import csv
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Tips for Exam:
• Write file open/close statements carefully.
• Remember mode meanings and combinations.
• Practice with both text and binary files.
— End of Chapter Notes —