Section A: Text File Programs
1. Write and Read a Text File
Program:
f = open("demo.txt", "w")
f.write("Hello Class 12\nFile Handling in Python")
f.close()
f = open("demo.txt", "r")
print(f.read())
f.close()
Output:
Hello Class 12
File Handling in Python
Explanation:
Program writes two lines into a text file and then reads and displays them.
2. Count Words in a File
Program:
f = open("demo.txt", "r")
data = f.read()
words = data.split()
print("Total words:", len(words))
f.close()
Output:
Total words: 6
Explanation:
Splits text into words using split() and counts them with len().
3. Count Vowels in a File
Program:
f = open("demo.txt", "r")
text = f.read().lower()
count = 0
for ch in text:
if ch in "aeiou":
count += 1
print("Total vowels:", count)
f.close()
Output:
Total vowels: 11
Explanation:
Counts vowels by iterating through file characters.
4. Count Lines in a File
Program:
f = open("demo.txt", "r")
lines = f.readlines()
print("Total lines:", len(lines))
f.close()
Output:
Total lines: 2
Explanation:
readlines() returns all lines as a list; len() counts them.
5. Display File Line by Line
Program:
f = open("demo.txt", "r")
for line in f:
print(line.strip())
f.close()
Output:
Hello Class 12
File Handling in Python
Explanation:
Reads file using a loop, printing each line.
6. Append Content to File
Program:
f = open("demo.txt", "a")
f.write("\nAppended line")
f.close()
f = open("demo.txt", "r")
print(f.read())
f.close()
Output:
Hello Class 12
File Handling in Python
Appended line
Explanation:
Appends a line without overwriting original content.
7. Count Occurrences of a Word in File
Program:
f = open("demo.txt", "r")
text = f.read().lower()
print("Occurrences of 'file':", text.count("file"))
f.close()
Output:
Occurrences of 'file': 2
Explanation:
Uses string count() method to count specific word.
Section B: Binary File Programs
1. Store and Retrieve Record
Program:
import pickle
f = open("student.dat", "wb")
record = {"Roll": 1, "Name": "Anmol", "Marks": 95}
pickle.dump(record, f)
f.close()
f = open("student.dat", "rb")
print(pickle.load(f))
f.close()
Output:
{'Roll': 1, 'Name': 'Anmol', 'Marks': 95}
Explanation:
Stores a dictionary in a binary file using pickle.
2. Store Multiple Records
Program:
import pickle
f = open("student.dat", "wb")
records = [{"Roll":1,"Name":"Anmol"},{"Roll":2,"Name":"Simran"}]
for r in records:
pickle.dump(r, f)
f.close()
Output:
File student.dat created with 2 records.
Explanation:
Multiple records stored using pickle.dump().
3. Read All Records
Program:
import pickle
f = open("student.dat", "rb")
try:
while True:
print(pickle.load(f))
except EOFError:
pass
f.close()
Output:
{'Roll': 1, 'Name': 'Anmol'}
{'Roll': 2, 'Name': 'Simran'}
Explanation:
Reads binary file till end using EOFError handling.
4. Search Record by Roll
Program:
import pickle
f = open("student.dat", "rb")
try:
while True:
rec = pickle.load(f)
if rec["Roll"] == 2:
print("Found:", rec)
except EOFError:
pass
f.close()
Output:
Found: {'Roll': 2, 'Name': 'Simran'}
Explanation:
Searches for specific Roll number.
5. Update Record Marks
Program:
import pickle
f = open("student.dat", "rb")
records = []
try:
while True:
records.append(pickle.load(f))
except EOFError:
pass
f.close()
for r in records:
if r["Roll"] == 1:
r["Marks"] = 99
f = open("student.dat", "wb")
for r in records:
pickle.dump(r, f)
f.close()
Output:
Record with Roll 1 updated to Marks 99.
Explanation:
Reads all records, modifies one, writes back.
6. Count Records in Binary File
Program:
import pickle
f = open("student.dat", "rb")
count = 0
try:
while True:
pickle.load(f)
count += 1
except EOFError:
pass
f.close()
print("Total Records:", count)
Output:
Total Records: 2
Explanation:
Counts number of records in a binary file.
7. Display Students with Marks > 90
Program:
import pickle
f = open("student.dat", "rb")
try:
while True:
rec = pickle.load(f)
if rec.get("Marks",0) > 90:
print(rec)
except EOFError:
pass
f.close()
Output:
{'Roll': 1, 'Name': 'Anmol', 'Marks': 99}
Explanation:
Filters and prints records with marks greater than 90.
Section C: CSV File Programs
1. Write and Read CSV File
Program:
import csv
f = open("student.csv", "w", newline="")
writer = csv.writer(f)
writer.writerow(["Roll","Name","Marks"])
writer.writerow([1,"Anmol",95])
f.close()
f = open("student.csv","r")
for row in csv.reader(f):
print(row)
f.close()
Output:
['Roll','Name','Marks']
['1','Anmol','95']
Explanation:
Writes and then reads a CSV file.
2. Append Record to CSV
Program:
import csv
f = open("student.csv", "a", newline="")
writer = csv.writer(f)
writer.writerow([2,"Simran",88])
f.close()
Output:
Record appended successfully.
Explanation:
Adds a new row to CSV without overwriting.
3. Read CSV using DictReader
Program:
import csv
f = open("student.csv","r")
reader = csv.DictReader(f)
for row in reader:
print(row["Roll"], row["Name"], row["Marks"])
f.close()
Output:
1 Anmol 95
2 Simran 88
Explanation:
DictReader allows accessing data by column names.
4. Count Records in CSV
Program:
import csv
f = open("student.csv","r")
reader = csv.reader(f)
count = sum(1 for row in reader) - 1
f.close()
print("Total Records:", count)
Output:
Total Records: 2
Explanation:
Counts records excluding header.
5. Search Record by Roll in CSV
Program:
import csv
f = open("student.csv","r")
reader = csv.DictReader(f)
for row in reader:
if row["Roll"] == "2":
print("Found:", row)
f.close()
Output:
Found: {'Roll':'2','Name':'Simran','Marks':'88'}
Explanation:
Searches a record using DictReader.
6. Display Students with Marks > 90 in CSV
Program:
import csv
f = open("student.csv","r")
reader = csv.DictReader(f)
for row in reader:
if int(row["Marks"]) > 90:
print(row)
f.close()
Output:
{'Roll':'1','Name':'Anmol','Marks':'95'}
Explanation:
Filters students by marks greater than 90.
7. Copy CSV Content to Another File
Program:
import csv
f1 = open("student.csv","r")
f2 = open("copy.csv","w",newline="")
writer = csv.writer(f2)
for row in csv.reader(f1):
writer.writerow(row)
f1.close()
f2.close()
Output:
File copied successfully.
Explanation:
Reads from one CSV file and writes into another.