File Handling Questions
Section A
1 Mark Question
1. A CSV file named students.csv contains the 1
following data: RollNo, Name, Class, Marks
101, Riya, 12, 89
102, Aarav, 12, 76
103, Isha, 12, 94
104, Kabir, 12, 67
A student writes the following
code: import csv
with open('students.csv',
'r') as f: reader =
csv.reader(f)
next(reader)
for row in reader:
if int(row[3]) > 80:
print(row[1],end=’,’)
What will be the output of the code?
a. Riya, Aarav, Isha,
b. Riya, Isha,
c. Isha, Kabir,
d. Aarav, Kabir,
2. If row[3] represents marks as a string from a CSV file, which is the correct way to 1
compare it numerically?
a. if int(row[3]) > 50:
b. if row[3] > 50:
c. if float(row) > 50:
d. if row > 50:
3. Correct syntax of writing single row in a csv file using writer object 1
a. writer.write(["Pencil","25"])
b. writer.writeline(["Pencil","25"])
c. writer.writerow(["Pencil","25"])
d. writer.append(["Pencil","25"])
4. Predict the output of following code : 1
import csv
f=
open("students.csv","w",newline=
"") w = csv.writer(f)
w.writerow([11,22,3
3]) f.close()
f=
open("students.csv",
"r") r = csv.reader(f)
for x in r:
print(x[0]+x
[1])
a. 33 b. 55 c. error d. 1122
5. Ms. Priyanka is trying to find out the output of the following code. Help her to find 1
the correct output of the code:
with open("data.txt", "w") as f:
f.writelines(["Line1\n", "Line2\n",
"Line3\n"])
with open("data.txt") as
f: print(f.readline())
a. Line1 b. ['Line1\n'] c. Line1\n d. Line2
6. Consider this code & find the output: 1
with open("temp.txt", "w") as f:
f.write("ABCDEF")
with open("temp.txt",
"r") as f: f.seek(3)
print(f.read(2))
a. AB b. CD c. DE d. EF
7. What will be the output of following code? 1
with open("notes.txt", "w") as f:
f.write("Python\nRocks")
with open("notes.txt",
"r") as f: for line in f:
print(line.strip())
a. Python b. Python
Rocks
c. Python\nRocks d. ['Python', 'Rocks']
8. What will be the output of the code 1
below? with open("log.txt", "w") as f:
f.write("12345")
with open("log.txt",
"r") as f:
print(f.read(3))
print(f.read(3))
a. 12345 b. 123 c. 123 d. 1
123 45 2
9. Which of the following statement opens a binary file record.bin in write mode and 1
writes data from a list
lst1 = [1,2,3,4]
a. with open('record.bin', 'wb') as myfile:
pickle.dump(myfile, lst1)
b. with
open('recor
d.bin',
'wb+') as
myfile:
pickle.dum
p(myfile,
lst1)
c. with open('record.bin', 'ab') as myfile:
pickle.dump(myfile, lst1)
d. with
open('reco
rd.bin',
'wb') as
myfile:
pickle.du
mp(lst1 ,
myfile)
10. Which of the following commands is used to open a binary file “c:\temp.dat” in 1
append- mode?
a. outfile= open(“c:/temp. dat”, “ab”)
b. outfile = open(“c:\temp. dat”, “wb+”)
c. outfile = open(“c:\temp. dat”, “ab”)
d. outfile = open(“c:\\temp. dat”, “r+b”)
11. What are the binary files used for? 1
a. To store ascii text
b. It is used to store data in the form of bytes.
c. To look folder good
d. None of these
12. Which of the following functions changes the position of file pointer 1
and returns its new position?
a.flush() b.tell() c.seek() d.offset()
13. The correct syntax of seek() is: 1
a. file_object.seek(offset [, reference_point])
b. seek(offset [, reference_point])
c. seek(offset, file_object)
d. seek.file_object(offset)
Following questions are Assertion (A) and Reason (R) based questions.
Mark the correct choice as:
a. Both A and R are true, and R is the correct explanation of A
b. Both A and R are true, but R is not the correct explanation of A
c. A is true, but R is false
d. A is false, but R is true
14. Assertion While writing data into a CSV file using csv.writer(),
(A): each row must be passed as a list or tuple.
Reason (R): The writerow() method of csv.writer class takes a single
string as input and writes it directly to the CSV file.
15. Assertion The csv.reader object in Python returns each row of a CSV file
(A): as a list.
Reason (R): Each row read by csv.reader can be accessed using a for loop.
16. Assertion In Python, a binary file must be opened using mode "rb" and
(A): "wb" for reading and writing respectively.
Reason (R): Binary files store data as text, which is compatible with
standard input/output functions like print().
17. Assertion Opening a file in 'a' mode raises an error if the file does
(A): not exist.
The 'a' mode also allows appending to existing files.
Reason (R):
18. Assertion f.seek(0) can be used to re-read a file from the
(A): beginning. seek() moves the file pointer to a specified
Reason location.
(R):
19. Assertion (A): Binary files store all data in text format.
Reasoning (R): Binary files data remain in its original type.
20. Assertion Using the 'with' statement to open a file is considered best
(A): practice. It ensures the file is automatically closed, even if an
Reason error occurs.
(R):
1. B) Riya, Isha
2. A) if int(row[3]) > 50:
3. C) writer.writerow(["Pencil","25"])
4. D) 1122
5. A) Line1
6. C) DE
7. A) Python
Rocks
8. C) 123
45
9. D) with open('record.bin', 'wb') as myfile:
pickle.dum
10.A) outfile = open(“c:/temp. dat”, “ab”)
11.B) It is used to store data in the form of bytes
12.C) seek()
13.A) file_object.seek(offset [, reference_point])
14.C)
15.A)
16.C)
17.D)
18.A)
19.D)
20.A)
Section B
2 Marks Question
1. Differentiate between rb+ and wb+ file modes in Python. 2
2. How are text files different from binary files in case of delimiter ? 2
3. Following code is written to display the total number of words present in the file 2
from a text file “Quotes.Txt”. Write statement 1 and 2 to complete the code.
def countwords():
s = open("Quotes.txt","r")
f = s.read()
___________________ statement 1
count = 0
____________________ statement 2
count = count + 1
print ("Total number of words:", count)
4. Write a function to display those lines which start with the letter “G” from the 2
text file “MyNotes.txt” Write statement 1 and statement 2 to complete the code.
def count_lines( ):
c=0
________________ statement 1
line = f.readlines()
for w in line:
_________________statement 2
print(w)
f.close()
5. Fill in the blank : 2
a) is a process of storing data into files and allows to performs various
tasks such as read, write, append, search and modify in files.
b) The transfer of data from program to memory (RAM) to permanent storage
device (hard disk) and vice versa are known as .
6. Write a Python program to create a CSV file named students.csv and store data 2
of
3 students (Name, Age, Class).
7. Write a program to read students.csv using DictReader and print names only. 2
8. Differentiate between writerow() and writerows()? 2
9. Differentiate between CSV file and Text file in case retrieval of records from 2
output file?
3 Marks Question
10. Write a function that counts and display the number of 5 letter words in a text 3
file
“Sample.txt“
11. Write a program to count the number of students in students.csv (excluding 3
header).
12. Write a program to read students.csv and display students older than 17. 3
13. Write a program to search for a student by name in students.csv? 3
14. A Binary file, CINEMA.DAT has the following structure: 3
{MNO:[MNAME, MTYPE]}
Where
MNO – Movie Number
MNAME – Movie Name
MTYPE is Movie Type
Write a user defined function, findType(mtype), that accepts mtype
as parameter and displays all the records from the binary file
CINEMA.DAT, that have the value of Movie Type as mtype.
15. Write a method/function COUNTLINES_ET() in python to read lines from a 3
text file REPORT.TXT, and COUNT those lines which are starting either with
‘E’ and starting with ‘T’ respectively. And display the Total count separately.
4 Marks Question
16. Consider a file, SPORT.DAT, containing records of the following 4
structure:
[SportName, TeamName, No_Players]
Write a function, CountRecord(),that count the number of records in the file.
Write a function, copyData(), that reads contents from the file SPORT.DAT and
copies the records with Sport name as “Cricket”to the file named
CRICKET.DAT, The function should return the total number of records copied
to the file
CRICKET.DAT.
17. Aman is a Python programmer. He has written a code and created a binary file 4
record.dat with employeeid, ename and salary. The file contains 10 records.He
now has to update a record based on the employee id entered by the user and
update the salary. The updated record is then to be written in the file temp.dat.
The records which are not to be updated also have to be written to the file
temp.dat. If the employee id is not found, an appropriate message should to be
displayed. As a Python expert, help him to complete the following code based
on the requirement given above:
import #Statement 1 def
update_data():
rec={}
fin=open("record.dat","rb")
fout=open(" ") #Statement 2
found=False
eid=int(input("Enter employee id to update their salary :: "))
while True:
try:
rec= #Statement 3
if rec["Employee
id"]==eid: found=True
rec["Salary"]=int(input("Enter new salary::
")) pickle #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a temporary file named
temp.dat. (Statement 2)
(iii) Which statement should Aman fill in Statement 3 to read the data from the
binary file, record.dat ?
(iv) Write Statement 4 to write the updated data in the file, temp.dat?
18. A binary file “Bank.dat” has structure as [account_no, cust_name,balance]. 4
i. Write a user-defined function addfile( ) and add a record to Bank.dat.
ii. Create a user-defined function CountRec( ) to count and return the number
of customers whose balance amount is more than 100000
5 Marks Question
19. A binary file “Stu.dat” has structure (rollno, name, marks). 5
(i) Write a function in Python add_record() to input data for a record and add
to Stu.dat.
(ii) Write a function in python Search_record() to search a record from
binary
file “Stu.dat” on the basis of roll number.
20. Amaira’s teacher asked her to count the no. of times words ‘he’ and ‘she’ 5
comes in a text file “poem.txt”. She wrote the code, but got confused in few
statements. Help her complete the following code.
f=open("poem.txt", “ ”) #Statement-1
data=f. #Statement-2 data=data.
#Statement-3 c=0
c1=0
for ch in data:
ch = ch. #Statement-4 if
ch=="HE" :
c=c+1
elif
ch=="
SHE":
c1+=1
print("No of She",c1)
print("No of he",c)
f. #Statement-5
i) Which of the following modes to be used in Statement-1while opening the
file?
a. W b. r c. a d.w+
ii) What should come in statement-2 to read all the contents of the file as a
single string?
a. read() b. readline() c. readlines() d. load()
iii) Which function should come in Statement-3 to get a list of words?
1. Answer:
rb+ mode:
· Opens a file for both reading and writing in binary format.
· The file must already exist; otherwise, an error occurs.
· The file pointer is placed at the beginning of the file.
· Existing content is preserved, and writing will overwrite from the current file pointer
position.
wb+ mode:
· Opens a file for both reading and writing in binary format.
· If the file exists, it is truncated (emptied); otherwise, a new file is created.
· The file pointer is placed at the beginning of the file.
· Any existing content is lost, and writing starts from the beginning of the file.
2. Answer:
Text Files:
· Store data as a sequence of characters (like ASCII or Unicode).
· Each line is terminated by a special character (EOL), typically a newline character
(\n).
· These delimiters are used to separate lines of text, allowing for easy reading and
writing of textual data.
Binary Files:
· Store data as a stream of bytes, without character encoding or line delimiters.
· There is no concept of "lines" in the same way as in text files.
· Binary files are typically used for storing data that is not intended for human readability,
such as images, audio, or program code.
3. Answer:
def countwords():
s = open("Quotes.txt", "r")
f = s.read()
words = f.split() # statement 1
count = 0
for word in words: # statement 2
count = count + 1
print ("Total number of words:", count)
4. Answer:
def count_lines( ):
c=0
with open(‘Quotes.txt’, 'r') as f:
line = f.readlines()
for w in line:
if line.strip().startswith('G'):
print(w)
f.close()
5. Answers:
a. File Handling
b. I/O Operations (Input/Output Operations)
6. Answer:
import csv
# Data for 3 students
students_data = [
['Alice', 15, '10th'],
['Bob', 16, '11th'],
['Charlie', 14, '9th']
]
# Define the header
header = ['Name', 'Age', 'Class']
# Create and write to the CSV file
with open('students.csv', 'w', newline='') as csvfile:
csv_writer = csv.writer(csvfile)
# Write the header
csv_writer.writerow(header)
# Write the student data
csv_writer.writerows(students_data)
print("students.csv created successfully with student data.")
7. Answer:
import csv
try:
with open('students.csv', 'r', newline='') as csvfile:
csv_reader = csv.DictReader(csvfile)
print("Names of students:")
for row in csv_reader:
print(row['Name'])
except FileNotFoundError:
print("Error: students.csv not found. Please run program 6 first to create it.")
8. Answer:
writerow(row):
a. This method is used to write a single row of data to the CSV file.
b. The row argument should be an iterable (like a list or tuple) where each element
represents a field in that row.
c. It adds a newline character after writing the row, effectively moving to the next
line in the CSV file.
Example:
writer.writerow(['John', 20, 'Grade A'])
writerows(rows):
d. This method is used to write multiple rows of data to the CSV file at once.
e. The rows argument should be an iterable of iterables (e.g., a list of lists or a list
of tuples), where each inner iterable represents a single row.
f. It iterates through the provided rows and calls writerow() internally for each
one.
Example:
data = [
['Alice', 15],
['Bob', 16]
]
writer.writerows(data)
9. Answer:
Basis CSV File Text File
Format Stores data in a tabular Stores data as plain text,
format (rows and columns) often without any structured
using commas to separate format.
values.
Data Retrieval Easier to retrieve specific More difficult to retrieve
records using programs (like specific records as data may
Python, Excel, etc.) because not be in a fixed format.
data is structured.
Usage Commonly used for Used for storing unstructured
databases, spreadsheets, or free-form text, such as
and structured data notes or logs.
exchange.
Readability by Program Can be easily read and Requires custom logic or
processed using parsing rules to extract data.
tools/libraries (like csv
module in Python).
10.Answer:
def count_5_letter_words():
"""
Counts and displays the number of 5-letter words in a text file.
"""
count = 0
try:
with open("Sample.txt", 'r') as file:
content = file.read()
words = [word.strip(".,!?;:\"'").lower() for word in content.split()]
for word in words:
if len(word) == 5:
count += 1
print(f"Number of 5-letter words in '{filepath}': {count}")
except FileNotFoundError:
print(f"Error: The file '{filepath}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
11.Answer:
import csv
def count_students_in_csv():
"""
Counts the number of student records in a CSV file, excluding the header.
"""
student_count = 0
try:
with open("students.csv", 'r', newline='') as file:
reader = csv.reader(file)
next(reader, None) # Skip the header row
for row in reader:
student_count += 1
print(f"Number of students in '{filepath}': {student_count}")
except FileNotFoundError:
print(f"Error: The file '{filepath}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
12.Answer:
import csv
def display_students_older_than(age_threshold, filepath="students.csv"):
"""
Reads a CSV file and displays students older than a specified age.
Args:
age_threshold (int): The age to compare against.
filepath (str): The path to the CSV file.
"""
found_students = False
try:
with open(filepath, 'r', newline='') as file:
reader = csv.reader(file)
header = next(reader, None) # Read header
if header:
try:
age_col_index = header.index("Age")
except ValueError:
print(f"Error: 'Age' column not found in '{filepath}'.")
return
else:
print(f"Error: '{filepath}' is empty or has no header.")
return
print(f"Students older than {age_threshold} in '{filepath}':")
for row in reader:
if len(row) > age_col_index: # Ensure row has enough columns
try:
age = int(row[age_col_index])
if age > age_threshold:
print(row) # Prints the entire row for the student
found_students = True
except ValueError:
print(f"Warning: Could not parse age for row: {row}")
continue # Skip to the next row if age is not an integer
else:
print(f"Warning: Row has fewer columns than expected: {row}")
if not found_students:
print(f"No students found older than {age_threshold}.")
except FileNotFoundError:
print(f"Error: The file '{filepath}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
display_students_older_than(17)
13.Answer:
import csv
def search_student_by_name(student_name, filepath="students.csv"):
"""
Searches for a student by name in a CSV file and displays their information.
Args:
student_name (str): The name of the student to search for.
filepath (str): The path to the CSV file.
"""
found_student = False
try:
with open(filepath, 'r', newline='') as file:
reader = csv.reader(file)
header = next(reader, None) # Read header
if header:
try:
name_col_index = header.index("Name")
except ValueError:
print(f"Error: 'Name' column not found in '{filepath}'.")
return
print(f"Searching for '{student_name}' in '{filepath}'...")
print(f"Header: {header}") # Display header for context
else:
print(f"Error: '{filepath}' is empty or has no header.")
return
for row in reader:
if len(row) > name_col_index: # Ensure row has enough columns
if row[name_col_index].lower() == student_name.lower():
print("Student found:")
# Print header and then the student's row for clear display
print(row)
found_student = True
break
if not found_student:
print(f"Student '{student_name}' not found in '{filepath}'.")
except FileNotFoundError:
print(f"Error: The file '{filepath}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
search_student_by_name("Alice")
print("\n---") # Separator for clarity
search_student_by_name("Bob")
print("\n---")
search_student_by_name("David") # Should not be found
14.Answer:
import pickle
def findType(mtype):
"""
Reads records from CINEMA.DAT and displays those with a matching movie type.
Args:
mtype (str): The movie type to search for.
"""
try:
with open("CINEMA.DAT", "rb") as file:
print(f"Records with Movie Type '{mtype}':")
found_records = False
while True:
try:
record = pickle.load(file)
# The structure is {MNO: [MNAME, MTYPE]}
# We need to iterate through the dictionary to access the MTYPE
for mno, details in record.items():
if details[1].lower() == mtype.lower(): # Case-insensitive comparison
print(f"Movie Number: {mno}, Movie Name: {details[0]}, Movie Type:
{details[1]}")
found_records = True
except EOFError:
break # End of file reached
if not found_records:
print(f"No records found with Movie Type '{mtype}'.")
except FileNotFoundError:
print("Error: CINEMA.DAT not found.")
except Exception as e:
print(f"An error occurred: {e}")
15.Answer:
def COUNTLINES_ET():
"""
Reads lines from REPORT.TXT, counts lines starting with 'E' or 'T',
and displays the individual counts and total count.
"""
e_count = 0
t_count = 0
total_count = 0
try:
with open("REPORT.TXT", "r") as file:
for line in file:
total_count += 1
stripped_line = line.strip() # Remove leading/trailing whitespace
if stripped_line.startswith('E') or stripped_line.startswith('e'):
e_count += 1
elif stripped_line.startswith('T') or stripped_line.startswith('t'):
t_count += 1
except FileNotFoundError:
print("Error: REPORT.TXT not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
print(f"Lines starting with 'E': {e_count}")
print(f"Lines starting with 'T': {t_count}")
print(f"Total lines checked: {total_count}") # Optional: show total lines processed
16.Answer:
import pickle
def CountRecord():
"""
Counts the number of records in the file SPORT.DAT.
Assumes SPORT.DAT contains pickled records, each a list like [SportName,
TeamName, No_Players].
"""
try:
with open("SPORT.DAT", "rb") as f:
count = 0
while True:
try:
pickle.load(f)
count += 1
except EOFError:
break
return count
except FileNotFoundError:
print("Error: SPORT.DAT not found.")
return 0
except Exception as e:
print(f"An error occurred in CountRecord: {e}")
return 0
def copyData():
"""
Reads records from SPORT.DAT and copies records with SportName "Cricket"
to CRICKET.DAT. Returns the total number of records copied.
"""
copied_count = 0
try:
with open("SPORT.DAT", "rb") as infile, open("CRICKET.DAT", "wb") as outfile:
while True:
try:
record = pickle.load(infile)
if record[0].lower() == "cricket": # Case-insensitive comparison for "Cricket"
pickle.dump(record, outfile)
copied_count += 1
except EOFError:
break
return copied_count
except FileNotFoundError:
print("Error: SPORT.DAT not found. No data copied.")
return 0
except IndexError:
print("Error: Record in SPORT.DAT does not have the expected structure
[SportName, TeamName, No_Players].")
return 0
except Exception as e:
print(f"An error occurred in copyData: {e}")
return 0
if __name__ == "__main__":
# Test CountRecord()
total_records = CountRecord()
print(f"\nTotal records in SPORT.DAT: {total_records}")
# Test copyData()
copied_records = copyData()
print(f"\nTotal 'Cricket' records copied to CRICKET.DAT: {copied_records}")
# Verify content of CRICKET.DAT (optional)
print("\nContent of CRICKET.DAT:")
try:
with open("CRICKET.DAT", "rb") as f:
while True:
try:
print(pickle.load(f))
except EOFError:
break
except FileNotFoundError:
print("CRICKET.DAT not found.")
except Exception as e:
print(f"Error reading CRICKET.DAT: {e}")
17.Answer:
import pickle # Statement 1
def update_data():
rec={}
fin=open("record.dat", "rb")
fout=open("temp.dat", "wb") # Statement 2
found=False
eid=int(input("Enter employee id to update their salary :: "))
while True:
try:
rec=pickle.load(fin) # Statement 3
if rec["Employee id"]==eid:
found=True
rec["Salary"]=int(input("Enter new salary:: "))
pickle.dump(rec, fout) # Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
18.Answer:
import pickle
def addfile():
"""
Adds a new bank record to the 'Bank.dat' binary file.
Each record contains account_no, cust_name, and balance.
"""
try:
with open("Bank.dat", "ab") as f:
while True:
print("\nEnter bank account details:")
account_no = input("Enter Account Number: ")
cust_name = input("Enter Customer Name: ")
while True:
try:
balance = float(input("Enter Balance: "))
if balance < 0:
print("Balance cannot be negative. Please enter a valid balance.")
else:
break
except ValueError:
print("Invalid input for balance. Please enter a number.")
# Create a dictionary to represent the record
record = {
"account_no": account_no,
"cust_name": cust_name,
"balance": balance
}
# Serialize and write the record to the binary file
pickle.dump(record, f)
print("Record added successfully!")
choice = input("Do you want to add another record? (yes/no): ").lower()
if choice != 'yes':
break
except IOError:
print("Error: Could not open or write to Bank.dat.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
def CountRec():
"""
Counts and returns the number of customers from 'Bank.dat'
whose balance amount is more than 100,000.
"""
count = 0
try:
# Open the file in read binary mode ('rb')
with open("Bank.dat", "rb") as f:
while True:
try:
# Deserialize and read one record at a time
record = pickle.load(f)
# Check if the balance is greater than 100,000
if record["balance"] > 100000:
count += 1
except EOFError:
# EOFError is raised when pickle.load() reaches the end of the file
break
except FileNotFoundError:
print("Error: 'Bank.dat' not found. Please add some records first.")
except Exception as e:
print(f"An unexpected error occurred while reading the file: {e}")
return count
if __name__ == "__main__":
print("--- Adding Records to Bank.dat ---")
addfile()
print("\n--- Counting Records with Balance > 100000 ---")
high_balance_customers = CountRec()
print(f"Number of customers with balance more than 100,000:
{high_balance_customers}")
19.Answer:
import pickle
def add_record():
"""
Inputs data for a student record (rollno, name, marks)
and appends it to the binary file "Stu.dat".
"""
try:
with open("Stu.dat", "ab") as file:
print("Enter student details:")
rollno = int(input("Roll Number: "))
name = input("Name: ")
marks = float(input("Marks: "))
record = {'rollno': rollno, 'name': name, 'marks': marks}
pickle.dump(record, file)
print("Record added successfully!")
except ValueError:
print("Invalid input. Please ensure Roll Number is an integer and Marks is a
number.")
except Exception as e:
print(f"An error occurred: {e}")
def Search_record(search_rollno):
"""
Searches for a student record in "Stu.dat" based on the given roll number.
Args:
search_rollno (int): The roll number to search for.
"""
found = False
try:
with open("Stu.dat", "rb") as file:
print(f"\nSearching for Roll Number: {search_rollno}")
while True:
try:
record = pickle.load(file)
if record['rollno'] == search_rollno:
print("\nRecord Found:")
print(f"Roll No: {record['rollno']}")
print(f"Name: {record['name']}")
print(f"Marks: {record['marks']}")
found = True
break
except EOFError:
break
except Exception as e:
print(f"Error reading record: {e}")
break
except FileNotFoundError:
print("The file 'Stu.dat' was not found. Please add records first.")
except Exception as e:
print(f"An error occurred: {e}")
if not found:
print(f"No record found for Roll Number {search_rollno}.")
add_record()
Search_record(101)
20.Answer:
a. B) r
b. A) read()
c. C) split()
d. D) upper()
e. B) close()