File Handling
1. Which of the following mode in file opening statement results or generates an error if the
file does not exist?
a) a+ (b) r+ (c) w+ (d) None of the above
2.The correct syntax of seek() is:
a)file_object.seek(offset [, reference_point] ) b) seek(offset [, reference_point])
c) seek(offset, file_object) (d ) seek.file_object(offset)
3.Which of the following is an invalid access mode for text files:
a) w b) a+ c) ab d) r
4. Which pickle module method is used to write a Python object to a binary file?
a. save() b. serialize() c. store() d. dump()
5. Which of the following file opening mode in Python, generates an error if the file does
not exist?
a) a b) r c) w d) w+
6. Which of the following functions changes the position of file pointer and returns its
new position?
a) flush() b) tell() c) seek() d) offset()
7. Which of the following option is not correct?
a. if we try to read a text file that does not exist, an error occurs.
b. if we try to read a text file that does not exist, the file gets created.
c. if we try to write on a text file that does not exist, no error occurs.
d. if we try to write on a text file that does not exist, the file gets Created.
8. Which of the following options can be used to read the first line of a text file Myfile.txt?
a. myfile = open('Myfile.txt'); myfile.read()
b. myfile = open('Myfile.txt','r'); myfile.read(n)
c. myfile = open('Myfile.txt'); myfile.readline()
d. myfile = open('Myfile.txt'); myfile.readlines()
9. Assume that the position of the file pointer is at the beginning of 3rd line in a text file.
Which of the following option can be used to read all the remaining lines?
a. myfile. read() b. myfile.read(n)
c. myfile.readline() d. myfile.readlines()
10. A text file student.txt is stored in the storage device. Identify the correct option out of
the following options to open the file in read mode.
i. myfile = open('student.txt','rb') ii. myfile = open('student.txt','w')
iii. myfile = open('student.txt','r') iv. myfile = open('student.txt')
a. only I b. both i and iv c. both iii and iv d. both i and iii
11. Which of the following statement is incorrect in the context of binary files?
a. Information is stored in the same format in which the information is held in memory.
b. No character translation takes place
c. Every line ends with a new line character
d. pickle module is used for reading and writing
12. What is the significance of the tell() method?
a. tells the path of file
b. tells the current position of the file pointer within the file
c. tells the end position within the file
d. checks the existence of a file at the desired location
13. Which of the following statement is true?
a. pickling creates an object from a sequence of bytes
b. pickling is used for object serialization
c. pickling is used for object deserialization
d. pickling is used to manage all types of files in Python
14. Syntax of seek function in Python is myfile.seek( offset, reference_point) where myfile is
the file object. What is the default value of reference_point?
a. 0 b. 1 c. 2 d. 3
15. Which of the following character acts as default delimiter in a csv file?
a. (colon) : b. (hyphen) - c. (comma) , d. (vertical line)
16. Syntax for opening Student.csv file in write mode is
myfile = open("Student.csv","w",newline='').
What is the importance of newline=''?
a. A newline gets added to the file b. Empty string gets appended to the first
line.
c. Empty string gets appended to all lines. d. EOL translation is suppressed
17. What is the correct expansion of CSV files?
a. Comma Separable Values b. Comma Separated Values
18. Which of the following is not a function / method of csv module in Python?
a. read() b. reader() c. writer() d. writerow()
19. Which one of the following is the default extension of a Python file?
a. .exe b. .p++ c. .py d. .p
20. Which of the following statement opens a binary file record.bin in write mode and writes
data from a list lst1 = [1,2,3,4] on the binary file?
a. with open('record.bin','wb') as myfile: b. with open('record.bin','wb') as myfile:
pickle.dump(lst1,myfile) pickle.dump(myfile,lst1)
c. with open('record.bin','wb+') as myfile: d. with open('record.bin','ab') as myfile:
pickle.dump(myfile,lst1) pickle.dump(myfile,lst1)
21. Which of the following methods will give the current position of the file pointer?
(a)seek() (b)tell() c)getloc() (d) None of the above
22. The default mode of opening a file in pyhton
(a) append (b) read (c) write (d) both b and c
2 MARKERS
1. Suppose content of 'Myfile.txt' is:
Twinkle twinkle little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
What will be the output of the following code?
myfile = open("Myfile.txt")
data = myfile.readlines()
print(len(data))
myfile.close()
a. 3 b. 4 c. 5 d. 6
2. Raghav is trying to write a tuple tup1 = (1,2,3,4,5) on a binary file test.bin. Consider the
following code written by him.
import pickle
tup1 = (1,2,3,4,5)
myfile = open("test.bin",'wb')
pickle._______ #Statement 1
myfile.close()
Identify the missing code in Statement 1.
a. dump(myfile,tup1) b. dump(tup1, myfile) c. write(tup1,myfile)
d. load(myfile,tup1)
3. A binary file employee.dat has following data :
def display(eno):
f=open("employee.dat","rb")
totSum=0
try:
while True:
R=pickle.load(f)
if R[0]==eno:
__________ #Line1
totSum = totSum + R[2]
except:
f.close()
print(totSum)
When the above mentioned function, display (103) is executed, the output displayed is
190000. Write appropriate jump statement from the following to obtain the above output.
a. jump b. break c. continue d. return
4. Suppose content of 'Myfile.txt' is
Honesty is the best policy.
What will be the output of the following code?
myfile = open("Myfile.txt")
x = myfile.read()
print(len(x))
myfile.close()
a. 5 b. 25 c. 26 d. 27
5. Suppose content of 'Myfile.txt' is
Culture is the widening of the mind and of the spirit.
What will be the output of the following code?
myfile = open("Myfile.txt")
x = myfile.read()
y = x.count('the')
print(y)
myfile.close()
a. 2 b. 3 c. 4 d. 5
6. Suppose content of 'Myfile.txt' is
Ek Bharat Shreshtha Bharat
What will be the output of the following code?
myfile = open("Myfile.txt")
vlist = list("aeiouAEIOU")
vc=0
x = myfile.read()
for y in x:
if(y in vlist):
vc+=1
print(vc)
myfile.close()
a. 6 b. 7 c. 8 d. 9
7.Suppose content of 'Myfile.txt' is
Twinkle twinkle little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle twinkle little star
What will be the output of the following code?
myfile = open("Myfile.txt")
line_count = 0
data = myfile.readlines()
for line in data:
if line[0] == 'T':
line_count += 1
print(line_count)
myfile.close()
a. 2 b. 3 c. 4 d. 5
8. Consider the following directory structure.
Suppose root directory (School) and present working directory are the same. What will
be the absolute path of the file Syllabus.jpg?
a. School/syllabus.jpg b. School/Academics/syllabus.jpg
c. School/Academics/../syllabus.jpg d. School/Examination/syllabus.jpg
9. If the csv file 'item.csv' has a header and 3 records in 3 rows and we want to display only
the header after opening the file with open() function, we should write
a). print(file.readlines()) b). print(file.read()) c). print(file.readline()) d).
print(file.header())
10.What is the purpose of the 'with' statement in file handling?
a. It is used for creating new files. b. It automatically closes the file when done.
c. It is used for reading binary files. d. It is used for appending data to files.
TEXT FILES
1. Write a method COUNTY() in Python to read content from text file ‘Text.txt’ and print total
number of words ending with letter ‘y’.
Example:
If the file ‘Text.txt’ content is as follows:
Shall I compare thee to a summer’s day? Thou
art more lovely and more temperate:
Rough winds do shake the darling buds of May, And
summer’s lease hath all too short a date;
The COUNTY() function should display the output as: 3
2. A pre-existing text file info.txt has some text written in it. Write a python function
countvowel() that reads the contents of the file and counts the occurrence of
vowels(A,E,I,O,U) in the file.
3.Write a function COUNT() in Python to read from a text file 'Gratitude.txt' and display the
count of
the letter 'e' in each line
Example: If the file content is as follows:
Gratitude is a humble heart's radiant glow,
A timeless gift that nurtures and bestows.
It's the appreciation for the love we're shown,
In moments big and small, it's truly known.
The COUNT() function should display the output as:
Line 1 : 3
Line 2 : 4
Line 3 : 6
Line 4 : 1
4. Write a function Start_with_I() in Python, which should read a text file 'Gratitude.txt'
and then display lines starting with 'I'.
Example: If the file content is as follows:
Gratitude is a humble heart's radiant glow,
A timeless gift that nurtures and bestows.
It's the appreciation for the love we're shown,
In moments big and small, it's truly known.
Then the output should be
It's the appreciation for the love we're shown,
In moments big and small, it's truly known.
5. Write a function in Python to read a text file, Alpha.txt and displays those lines which
begin with the word ‘You’.
6. Write a function, vowelCount() in Python that counts and displays the number of vowels
in the text file named Poem.txt.
7.Write a function,Count() in Python that counts and displays the number of words in the
text file named sample.txt. 8. Write a function in Python that counts the number of “Me” or
“My” words present in a text file
“STORY.TXT”.
If the “STORY.TXT” contents are as follows:
My first book was
Me and My Family.
It gave me chance to be
Known to the world.
The output of the function should be: Count of Me/My in file: 4
9. Write a function AMCount() in Python, which should read each character of a text file
STORY.TXT, should count and display the occurance of alphabets A and M (including small
cases a and m too).
Example: If the file content is as follows:
Updated information As simplified by official websites.
The AMCount() function should display the output as:
A or a:4
M or m :2
10. Write a function in python to count the number of lines in a text file ‘STORY.TXT’ which
is starting with an alphabet ‘A’ .
11. Write a method/function DISPLAYWORDS() in python to read lines from a text file
TORY.TXT, and display those words, which are less than 4 characters.
12. Write the definition of a function Count_Line() in Python, which should read each line of
a text file "SHIVAJI.TXT" and count total number of lines present in text file.
For example, if the content of the file "SHIVAJI.TXT" is as follows:
Shivaji was born in the family of Bhonsle.
He was devoted to his mother Jijabai.
India at that time was under Muslim rule.
The function should read the file content and display the output as follows:
Total number of lines: 3
13. Write a function count Words() in Python to count the words ending with a digit in a text
file "Details.txt".
Example: If the file content is as follows:
On seat2 VIP1 will sit and
On seat1 VVIP2 will be sitting
Output will be:
Number of words ending with a digit are 4
14. Write the definition of a Python function named LongLines ( ) which reads the contents
of a text file named 'LINES.TXT' and displays those lines from the file which have at least 10
words in it.
BINARY FILES
1.A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write
a function countrec() in Python that would read contents of the file “STUDENT.DAT” and
display the details of those students whose percentage is above 75. Also display number of
students scoring above 75%
2. Consider a binary file 'INVENTORY.DAT' that stores information about products using
tuple with the structure (ProductID, ProductName, Quantity, Price). Write a Python function
expensiveProducts() to read the contents of 'INVENTORY.DAT' and display product-id with a
price higher than Rs.1000. Additionally, calculate and display the total count of such
expensive products.
For example: If the file stores the following data in binary format
(1, 'ABC', 100, 5000)
(2, 'DEF', 250, 1000)
(3, 'GHI', 300, 2000)
then the function should display
Product ID: 1
Product ID: 3
Total expensive products: 2
3. i. Mention any two differences between seek() and tell().
ii. Consider a file FLIGHT.DAT containing multiple records. The structure of each record
is as shown below: [ Fno, FName, Fare, Source, Destination]
Write a function COPY_REC() in Python that copies all those records from FLIGHT.DAT
where the source is DELHI and the destination is MUMBAI, into a new file
RECORD.DAT
4. i. Mention any two differences between binary files and csv files?
ii. Consider a Binary file BOOK.DAT containing a dictionary having multiple elements.
Each element is in the form BNO:[BNAME,BTYPE,PRICE] as key:value pair where
BNO – Book Number
BNAME – Book Name
BTYPE - Book Type
PRICE – Book price
Write a user-defined function, findBook(price), that accepts price as parameter and displays
all those records from the binary file BOOK.DAT which has a book price more than or equal
to the price value passed as a parameter.
5. i). Differentiate between r+ and w+ file modes in Python.
ii)Consider a file, SPORT.DAT, containing records of the following structure:
[SportName, TeamName, No_Players]
Write a function, copyData(), that reads contents from the file SPORT.DAT and
Copies the records with Sport name as “Basket Ball” to the file named BASKET.DAT.
The function should return the total number of records copied to the file BASKET.DAT.
6. A Binary file, CINEMA.DAT has the following structure: {MNO:[MNAME, MTYPE]}
Where MNO – Movie Number MNAME – Movie Name M TYPE 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.As a Python expert, help Rehaan to complete the following code based on the
requirement given:
import ________________#Statement 1
def update_data():
rec={ }
fin=open("record.dat","rb")
fout=open(" __________________") #Statement 2
found=False
sid=int(input("Enter student id to update their marks :: ")) while True:
try:
rec=__________________ #Statement 3
if rec["Student_id"]==sid:
found=True
rec["Marks"]=int(input("Enter new marks :: "))
pickle._________________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The mark of student id ",sid," has been updated.")
else:
print("No student with such id is 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 Rehaan fill in Statement 3 to read the data from the binary
filerecord.dat, and in Statement 4 to write the updated data in the file, temp.dat?
7. Aman is a Python programmer. He has written a code and created a binary file 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 and in Statement 4 to write the updated data in the file, temp.dat?
8. i) Differentiate between “w” and “a” file modes in Python.
ii) Consider a file, CINEMA.DAT, containing records of the following structure:
[MovieName, Movie_ID, No_of_theatres]
Write a function, copy(), that reads contents from the file CINEMA.DAT and copies the
records with Movie name as “ KAALAI” to the file named kaalai.DAT. The function should
return the total number of records copied to the file COPY.DAT.
9. i) Differntiate seek() and tell() methods in python. (2+3)
ii) A Binary file, CINEMA.DAT has the following structure:
{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.
CSV FILES
1. What is the advantage of using a csv file for permanent storage?
Write a Program in Python that defines and calls the following user defined functions:
ADDPROD() – To accept and add data of a product to a CSV file ‘product.csv’. Each record
consists of a list with field elements as prodid, name and price to store product id, product
name and product price respectively.
COUNTPROD() – To count the number of records present in the CSV file named
‘product.csv’.
2. Give any one point of difference between a binary file and a csv file.
Write a Program in Python that defines and calls the following user defined functions:
. (i) add() – To accept and add data of a to a CSV file ‘stud.csv’. Each record consists of a
list with field elements as admno, sname and per to store admission number,
student name and percentage marks respectively.
(ii) search()- To display the records of the students whose percentage is more than 75.
3.Create a function maxsalary() in Python to read all the records from an already existing
File record.csv which stores the records of various employees working in a department.
Data is stored under various fields as shown below:
Function should display the row where the salary is maximum.
Note: Assume that all employees have distinct salary.
4.Vedansh is a Python programmer working in a school. For the Annual Sports Event, he
has created a csv file named Result.csv, to store the results of students in different sports
events.
The structure of Result.csv is : [St_Id, St_Name, Game_Name, Result]
Where St_Id is Student ID (integer)
ST_name is Student Name (string)
Game_Name is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Won', 'Lost' or 'Tie'
For efficiently maintaining data of the event, Vedansh wants to write the following user
defined functions:
Accept() – to accept a record from the user and add it to the file Result.csv. The column
headings should also be added on top of the csv file.
wonCount() – to count the number of students who have won any event. As a Python expert,
help him complete the task.
5. What is the advantage of using a csv file for permanent storage?
Write a Program in Python that defines and calls the following user defined functions:
ADD() – To accept and add data of an employee to a CSV file ‘record.csv’. Each record
consists of a list with field elements as empid, name and salary to store employee id,
employee name and employee salary respectively.
COUNTR() – To count the number of records present in the CSV file named ‘record.csv’.
6.Give any one point of difference between a binary file and a csv file.
Write a Program in Python that defines and calls the following user defined functions:
add() – To accept and add data of an employee to a CSV file ‘furdata.csv’. Each record
consists of a list with field elements as fid, fname and fprice to store furniture id, furniture
name and furniture price respectively.
search()- To display the records of the furniture whose price is more than 10000.
7. Raju is a python programmer working in a leading software company in Chennai. He is
assigned with a task to provide the employee name for their annual appreciation with
incentive. For this he created a csv file named “incentive.csv” to store the names of the
employee in different criteria.
The structure of the file is: [Emp_id, Emp_Name, Emp_Designtion,No of Incentives received ]
He needs to write a user defined functions that performs the following tasks
Accept() – to accept the details from the user and add it to the file.
Incentive() – to display the name of employee who received incentive more than 3 times.
*The file “incentive.csv” should have a proper title.
8.Write a program in python that defines and calls the following user defined functions:
1) Courier_Add(): It takes the values from the user and adds the details to csv file
“Courier.csv”, Each record consists of a list with fields elements as cid, s_name,
Source, destination to store courier ID, Sender_Name, Source and destination address
respectively.
2) Courier_Search(): Takes the destination as the input and displays all the courier
records going to that destination.
9. Write a program in python that defines and calls the following user defined functions:
1) Add_Book(): Takes the details of the books and adds them to a csv file
“Book.CSV”.each record consists of a list with field elements as book_id,b_name and
publication to store book id, book name and publisher respectively.
2) Search_Book(): Takes publisher name as input and counts and displays number of
books published by them.
ASSERTION AND REASONING
ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
d) A is false but R is True
1. Assertion (A):- If the arguments in function call statement match the number and order of
arguments as defined in the function definition, such arguments are called positional
arguments.
Reasoning (R):- During a function call, the argument list first contains default
argument(s) followed by positional argument(s).
2. Assertion (A): CSV (Comma Separated Values) is a file format for data storage which looks
like a text file.
Reason (R): The information is organized with one record on each line and each field
is separated by comma.
3. Assertion (A) : A variable defined outside any function or any block is known as a global
variable.
Reason ( R ) : A variable defined inside any function or a block is known as a local variable
4 Assertion (A ) : The tell( ) method returns an integer that specifies the current position of
the file object in the file.
Reason ( R) : Offset can have any of the three values – 0, 1 and 2
5.Assertion (A):- If the arguments in function call statement match the number and order of
arguments as defined in the function definition, such arguments are called positional
arguments.
Reasoning (R):- During a function call, the argument list first contains default argument(s)
followed by positional argument(s).
6. Assertion (A): CSV (Comma Separated Values) is a file format for data storage which looks
like a text file.
Reason (R): The information is organized with one record on each line and each field is
separated by comma.
7. Assertion (A): For changes made to a variable defined within a function to be visible
outside the function, it should be declared as global.
Reasoning (R): Variables defined within a function are local to that function by default,
unless explicitly specified with the global keyword.
8. Assertion (A): A binary file in python is used to store collection objects like lists and
dictionaries that can be later retrieved in their original form using pickle module.
Reasoning (A): Binary files are just like normal text files and can be read using a text editor
like Notepad.
9. Assertion(A): List is an immutable data type
Reasoning(R): When an attempt is made to update the value of an immutable variable, the
old variable is destroyed and a new variable is created by the same name in memory.
10. Assertion(A): Python standard library consists of number of modules.
Reasoning(R): A function in a module is used to simplify the code and avoids repetition.
11. Assertion (A) : Default arguments in Python functions should always be placed before
non-default arguments in the function signature.
Reasoning(R): Placing default arguments before non-default arguments ensures that the
function can be called without specifying values for the default arguments if needed.
12. Assertion (A) : Fiber-optic cables are considered superior to twisted-pair cables for high-
speed data transmission.
Reasoning (R) : Fiber-optic cables use light signals to transmit data, which can travel at
higher speeds and over longer distances compared to the electrical signals used in twisted-
pair cables.
13. Assertion (A):- If the arguments in function call statement match the number and order
of arguments as defined in the function definition, such arguments are called positional
arguments.
Reasoning (R):- During a function call, the argument list first contains default argument(s)
followed by positional argument(s).
14. Assertion (A): CSV (Comma Separated Values) is a file format for data storage which
looks like a text file.
Reason (R): The information is organized with one record on each line and each field is
separated by comma.