File Handling Q&A
File Handling Q&A
○ Use basic file I/O methods: open(), read(), readlines(), write(), close().
○ Requires correct file modes: 'a' for append, 'r' for reading.
✅ Writing
with open("story.txt", "w") as f:
f.write("This is a new line.\n")
✅ Appending
with open("story.txt", "a") as f:
f.write("Adding more content.\n")
✅
"Emails.txt".
Answer:
def show():
f = open("Email.txt", 'r')
data = f.read()
words = data.split()
for word in words:
if '@cmail' in word:
print(word, end=' ')
f.close()
Question 29B
Write a Python function that finds and displays all the words longer than 5 characters from a
✅
text file "Words.txt".
Answer:
def display_long_words():
with open("Words.txt", 'r') as file:
data = file.read()
words = data.split()
for word in words:
if len(word) > 5:
print(word, end=' ')
🔹 From Section D (4 Marks)
Question 33
The CSV file "Happiness.csv" contains:
● Country Name
● Population
● Sample Size
● Number of Happy People
Part I: Display records with population > 5,000,000
✅
Answer:
def show():
import csv
f = open("happiness.csv", 'r')
records = csv.reader(f)
next(records, None) # To skip the Header row
for i in records:
if int(i[1]) > 5000000:
print(i)
f.close()
Part II: Count the number of records
✅
Answer:
def Count_records():
import csv
f = open("happiness.csv", 'r')
records = csv.reader(f)
next(records, None)
count = 0
for i in records:
count += 1
print(count)
f.close()
✅
Answer:
import pickle
def input_candidates():
candidates = []
n = int(input("Enter the number of candidates you want to add: "))
for i in range(n):
candidate_id = int(input("Enter Candidate ID: "))
candidate_name = input("Enter Candidate Name: ")
designation = input("Enter Designation: ")
experience = float(input("Enter Experience (in years): "))
candidates.append([candidate_id, candidate_name, designation,
experience])
return candidates
candidates_list = input_candidates()
def append_candidate_data(candidates):
with open('candidates.bin', 'ab') as file:
for candidate in candidates:
pickle.dump(candidate, file)
print("Candidate data appended successfully.")
✅
Part II: Update designation to “Senior Manager” if experience > 10
Answer:
def update_senior_manager():
updated_candidates = []
try:
with open('candidates.bin', 'rb') as file:
while True:
try:
candidate = pickle.load(file)
if candidate[3] > 10:
candidate[2] = 'Senior Manager'
updated_candidates.append(candidate)
except EOFError:
break
except FileNotFoundError:
print("No candidate data found.")
return
print("Candidates updated.")
✅
Part III: Display non-Senior Managers
Answer:
def display_non_senior_managers():
try:
with open('candidates.bin', 'rb') as file:
while True:
try:
candidate = pickle.load(file)
if candidate[2] != 'Senior Manager':
print(f"Candidate ID: {candidate[0]}")
print(f"Candidate Name: {candidate[1]}")
print(f"Designation: {candidate[2]}")
print(f"Experience: {candidate[3]}")
print("--------------------")
except EOFError:
break
except FileNotFoundError:
print("No candidate data found.")
✅📝
(d) F.seek(0,2)
Answer: (c) F.seek(0,-1)
This is invalid because negative offset with mode 0 (absolute) is not allowed.
Q17 (Assertion/Reason):
Assertion (A): CSV file is a human-readable text file where each line has a number of fields,
separated by comma or some other delimiter.
✅Reason (R): writerow() method is used to write a single row in a CSV file.
Answer: (b) Both A and R are true, and R is not the correct explanation for A.
✅ Section C – 3 Marks
Q28 (A):
Write a Python function showInLines() that reads content from a text file STORY.TXT and
displays each sentence on a new line.
A sentence ends with ., ?, or !.
✅ Answer (Sample):
def showInLines():
with open("STORY.TXT", 'r') as F:
S = F.read()
for W in S:
if W in ".!?":
print(W)
elif W == "\n":
continue
else:
print(W, end="")
Q28 (B):
Write a function c_words() in Python that counts and displays the number of uppercase and
✅
lowercase letters in a file Words.txt.
Answer (Sample):
def c_words():
with open("Words.txt", "r") as f:
text = f.read()
CL = CU = 0
for ch in text:
if ch.islower():
CL += 1
elif ch.isupper():
CU += 1
print(CL, CU)
✅ Section D – 4 Marks
Q32:
A CSV file "Peripheral.csv" has records [P_id, P_name, Price].
Write:
(i) Add_Device(): to input a record and append it to the file.
def Add_Device():
with open("Peripheral.csv", "a", newline='') as f:
writer = csv.writer(f)
P_id = int(input("Enter ID: "))
P_name = input("Enter Name: ")
Price = int(input("Enter Price: "))
writer.writerow([P_id, P_name, Price])
def Count_Device():
with open("Peripheral.csv", "r") as f:
reader = csv.reader(f)
count = 0
for row in reader:
if int(row[2]) < 1000:
count += 1
print(count)
✅ Section E – 5 Marks
Q34 (A)(ii):
A binary file items.dat has records {item_id: [item_name, amount]}.
Write a function Copy_new() that copies records with amount > 1000 into
✅
new_items.dat.
Answer (Sample):
import pickle
def Copy_new():
with open("items.dat", "rb") as fin, open("new_items.dat", "wb")
as fout:
try:
data = pickle.load(fin)
new_data = {k: v for k, v in data.items() if v[1] > 1000}
pickle.dump(new_data, fout)
except EOFError:
pass
Q34 (B)(ii):
Binary file EMP.DAT has records: [Emp_Id, Name, Salary].
✅
Write disp_Detail() to display details of employees with Salary < 25000.
Answer (Sample):
import pickle
def disp_Detail():
try:
with open("EMP.DAT", "rb") as f:
while True:
try:
data = pickle.load(f)
for record in data:
if record[2] < 25000:
print(record)
except EOFError:
break
except FileNotFoundError:
print("File Not Found!")
✅
Q23(b): Mode to open the file to add data in Line 2.
Answer: 'a' or 'a+' or 'append'
✅
Q23(c): Mode to open the file to read data in Line 3.
Answer: 'r' or 'r+' or 'read'
✅ Answer: close()
Q23(e): Fill in the blank in Line 5 to close the file.
✅
Replace every "he" with "she" in "BIOPIC.TXT".
Answer:
python
CopyEdit
def ChangeGender():
f = open("BIOPIC.TXT", 'r')
Text = f.read()
print(Text.replace(' he ', ' she '))
f.close()
✅
Count total number of lines in "SHIVAJI.TXT".
Answer:
python
CopyEdit
def Count_Line():
f = open("SHIVAJI.TXT", 'r')
Lines = f.readlines()
print('Total number of lines :', len(Lines))
f.close()
📄 Question 40: Binary File Handling – PLANTS.dat
✅
(a) WRITEREC() – To write records to a binary file.
Answer:
python
CopyEdit
import pickle
def WRITEREC():
f = open("PLANTS.dat", "wb")
data_log = []
while True:
ID = int(input("Enter ID:"))
NAME = input("Enter Name:")
PRICE = float(input("Enter Price:"))
data_log.append([ID, NAME, PRICE])
Choice = input("Add more? (Yes/No): ")
if Choice.lower().startswith('n'):
break
pickle.dump(data_log, f)
f.close()
✅
(b) SHOWHIGH() – To display records with PRICE > 500.
Answer:
python
CopyEdit
def SHOWHIGH():
import pickle
f = open("PLANTS.dat", "rb")
try:
while True:
data = pickle.load(f)
for record in data:
if record[2] > 500:
print("ID:", record[0])
print("Name:", record[1])
print("Price:", record[2])
print()
except:
f.close()
📄 Alternative Option in Q40: PATIENTS.dat – countrec()
✅
Function to display and count records where disease is 'COVID-19'
Answer:
python
CopyEdit
import pickle
def countrec():
f = open("PATIENTS.dat", "rb")
N = 0
try:
while True:
data = pickle.load(f)
for record in data:
if record[2] == 'COVID-19':
print("PID:", record[0])
print("NAME:", record[1])
print("DISEASE:", record[2])
N += 1
except:
f.close()
print('Total number of Covid-19 Patients =', N)