Class 12 Computer Science – Notes
1. Text File Handling
Text files store data in human-readable form (characters).
Syntax:
f = open("filename.txt", "mode")
Modes:
"r" → read
"w" → write (overwrites existing file)
"a" → append
"r+" → read and write
"w+" → write and read
"a+" → append and read
Example:
f = open("test.txt", "w")
f.write("Hello, world!")
f.close()
f = open("test.txt", "r")
print(f.read())
f.close()
2. Binary File Handling
Binary files store data in binary (0s and 1s). Used for images, videos, etc.
Syntax:
f = open("filename.dat", "mode")
Modes:
"rb" → read binary
"wb" → write binary
"ab" → append binary
Example:
import pickle
data = ["Python", "File Handling", 12]
f = open("data.dat", "wb")
pickle.dump(data, f)
f.close()
f = open("data.dat", "rb")
content = pickle.load(f)
print(content)
f.close()
3. CSV File Handling
CSV (Comma Separated Values) files store tabular data where each line is a row.
Syntax:
import csv
# Writing CSV
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
writer.writerow(["Akshat", 17])
# Reading CSV
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
4. Random Module
The random module is used to generate random numbers and make random choices.
Common Functions & Syntax:
import random
random.random() → returns float between 0.0 and 1.0
random.randint(a, b) → returns int between a and b (inclusive)
random.randrange(start, stop, step) → random int from range
random.choice(sequence) → returns random element from list/string
random.shuffle(list) → shuffles the list in place
random.uniform(a, b) → returns float between a and b
Example:
import random
print(random.random()) # 0.234...
print(random.randint(1, 10)) # e.g., 7
print(random.randrange(2, 20, 2)) # even number between 2 and 20
print(random.choice(["red", "blue", "green"]))
lst = [1, 2, 3, 4]
random.shuffle(lst)
print(lst)
print(random.uniform(1, 5))