Class-12-File Handling

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

L = S.

split ()
Data file handling 1 mark questions computer science for i in L:
class 12 if len (i)%3!=0:
[1] Consider the following directory structure. print (i, end= " ")
computer science class 12 previous year questions file a) Baa baa you any
handling 1 mark questions b) black have wool?
Suppose the present working directory is MyCompany. c) black sheep, have wool?
What will be the relative path of the file Transactions.Dat? d) Error
a) MyCompany/Transactions.Dat
b) MyCompany/Accounts/Transactions.Dat [6] Suppose the content of a text file “Rhymes.txt” is as
c) Accounts/Transactions.Dat follows:
d) ../Transactions.Dat Jack & Jill
went up the hill
[2] Suppose the content of “Rhymes.txt” is: What will be the output of the following Python code ?
Hickory Dickory Dock F = open ("Rhymes.txt")
The mouse went up the clock L = F.readlines ()
F = open ("Rhymes. txt") for i in L:
L = F. readlines () S=i.split()
X = ["the", "ock"] print (len (S) ,end="#")
for i in L: a) 2#4#
for W in i.split () :
if W in X: b) 3#4#
print (W, end = "*")
a) the* c) 2#
b) Dock*The*the*clock*
c) Dock*the*clock* d) 7#
d) Error
[7] Which of the following function is used with the csv
[3] Suppose the content of “Rhymes.txt” is: module in Python to read of the contents a csv file into an
Good Morning Madam object?
What will be the output of the following Python code? a) readrow()
b) readrows()
F = open ("Rhymes.txt") c) reader()
L = F.read ().split () d) load()
for W in L: Ans.: c) reader()
if W.lower () == W[::-1].lower ():
print (W) [8] Which of the following Python modules is imported to
a) Good store and retrieve objects using the process of
b) Morning serialization and deserialization?
c) Madam a) csv
d) Error b) binary
c) math
[4] Suppose the content of “Rhymes.txt” is: d) pickle
One, two, three, four, five
Once. I caught a fish alive. [9] Suppose the content of a text file Notes.txt is:
What will be the output of the following Python code? The way to get started is to quit talking and begin doing
F = open ("Rhymes.txt") What will be the output of the following Python code?
S = F.read () F = open ("Rhymes.txt")
print (S.count('e',20)) F.seek (29)
a) 20 S= F.read ()
b) 1 print (S)
c) 3 a) The way to get started is to
d) 6 b) quit talking and begin doing
[5] Suppose the content of “Rhymes.txt” is: c) The way to get started is to quit talking and begin doing
Baa baa black sheep d) gniod nigeb dna gniklat tiuq ot si detrats teg ot yaw ehT

have you any wool? [10] Which of the following is the default character for the
What will be the output of the following Python code? newline parameter for a csv file object opened in write
F = open ("Rhymes.txt") mode in Python IDLE ?
S = F.read () a) \n
b) \t
c) , a) F = open(“Notes.txt”,”w”)
d) ;
b) F = open(“Notes.txt”,”a”)
[11] If the following statement is used to read the
contents of a textfile object F: X-F.readlines( ) c) F = open(“Notes.txt”,”A”)

Which of the following is the correct data type of x? d) F = open(“Notes.txt”,”w+”)


a) list
b) dictionary [18] Which of the following is the correct python
c) string statement to read and display the first 10 characters from
d) tuple a text file Notes.txt?
a) F = open(“notes.txt”);print(F.load(10))
[12] Which of the following is the correct expansion of b) F = open(“notes.txt”);print(F.dump(10))
CSV ? c) F = open(“notes.txt”);print(F.read(10))
a) Comma Separated Values d) F = open(“notes.txt”);print(F.write(10))
b) Centrally Secured Values [19] Which of the following statement is not correct?
c) Computerised Secured Values a) We can write content into text file opened using ‘w’
d) Comma Secured Values mode
b) We can write content into text file opened using ‘w+’
[13] What is the significance of the seek() method? mode
a) It seeks the absolute path of the file c) We can write content into text file opened using ‘r’
b) It tells the current byte position of the file pointer mode
within the file d) We can write content into text file opened using ‘r+’
c) It places the file pointer at the desired offset within the mode
file
d) It seeks the entire content of the file [20] Which of the following is a function/method of the
pickle module?
Ans.: c) It places the file pointer at the desired offset a) reader()
within the file b) load()
[14] Which of the following statement is incorrect in the c) writer()
context of pickled binary files? d) read()
a) csv module is used for reading and writing objects in
binary files [21] Suppose content of ‘Myfile.txt’ is :
b) pickle module is used for reading and writing objects in Ek Bharat Shreshtha Bharat
binary files What will be the output of the following code?
c) load () of the pickle module is used to read objects myfile = open("Myfile.txt")
d) dump () of the pickle module is used to write objects vlist = list("aeiouAEIOU")
vc=0
[15] Which of the following option is the correct usage for x = myfile.read()
the tell() of a file object? for y in x:
a) It places the file pointer at the desired offset in a file if(y in vlist):
b) It returns the entire content of a file vc+=1
c)It returns the byte position of the file pointer as an print(vc)
integer myfile.close()
d) It tells the details about the file a. 6
b. 7
[16] A text file opened using following statement: c. 8
MyFile =open(‘Notes.txt’) d. 9
Which of the following is the correct statement to close
it? [22] Which of the following statement is incorrect in the
a) MyFile=close(‘Notes.txt’) context of binary files?
b) MyEile.close ( ‘Notes.txt’) a. Information is stored in the same format in which the
c) close.MyFile () information is held in memory.
d) MyFile.close () b. No character translation takes place

c. Every line ends with a new line character


[17] Which of the following is not a correct python d. pickle module is used for reading and writing
statement to open a text file “Notes.txt” to write content
into it? [23] Which of the following statement is not true?
a. pickling creates an object from a sequence of bytes Like a diamond in the sky “
b. pickling is used for object serialization What will be the output of the following code?
c. pickling is used for object deserialization myfile = open("Myfile.txt")
d. pickling is used to manage all types of files in Python data = myfile.readlines()
print(len(data))
myfile.close()
[24] Syntax of seek function in Python is a. 3
myfile.seek(offset, reference_point) where myfile is the b. 4
file object. What is the default value of reference_point? c. 5
a. 0 d. 6
b. 1
c. 2 [31] Raghav is trying to write a tuple tup1 = (1,2,3,4,5) on
d. 3 a binary file test.bin. Consider the following code written
by him.
[25] Which of the following character acts as default import pickle
delimiter in a csv file? tup1 = (1,2,3,4,5)
a. (colon) : myfile = open("test.bin",'wb')
b. (hyphen) – pickle._______ #Statement 1
c. (comma) , myfile.close()
d. (vertical line) | Identify the missing code in Statement 1.
a. dump(myfile,tup1)
[26] Syntax for opening Student.csv file in write mode is b. dump(tup1, myfile)
myfile = open(“Student.csv”,”w”,newline=”). What is the c. write(tup1,myfile)
importance of newline=”? d. load(myfile,tup1)
a. A newline gets added to the file
b. Empty string gets appended to the first line [32] A binary file employee.dat has the following data :
c. Empty string gets appended to all lines empno ename salary
d. EOL translation is suppressed 101 Anuj 50000
102 Arijita 40000
[27] What is the correct expansion of CSV files? 103 Hanika 30000
a. Comma Separable Values 104 Firoz 60000
b. Comma Separated Values 105 VijayLakshmi 40000
c. Comma Split Values def display(eno):
d. Comma Separation Values f=open("employee.dat","rb")
totSum=0
[28] Which of the following is not a function / method of try:
csv module in Python? while True:
a. read() R=pickle.load(f)
b. reader() if R[0]==eno:
c. writer() __________ #Line1
d. writerow() totSum=totSum+R[2]
except:
[29] Which of the following statement opens a binary file f.close()
record.bin in write mode and writes data from a list lst1 = print(totSum)
[1,2,3,4] on the binary file? When the above-mentioned function, display (103) is
a. with open(‘record.bin’,’wb’) as myfile: executed, the output displayed is 190000.
pickle.dump(lst1,myfile) Write an appropriate jump statement from the following
b. with open(‘record.bin’,’wb’) as myfile: to obtain the above output.
pickle.dump(myfile,lst1) a. jump
c. with open(‘record.bin’,’wb+’) as myfile: b. break
pickle.dump(myfile,lst1) c. continue
d. with open(‘record.bin’,’ab’) as myfile: d. return
pickle.dump(myfile,lst1)

[33] A text file student.txt is stored in the storage device.


Identify the correct option out of the following options to
[30] Suppose the content of ‘Myfile.txt’ is: open the file in reading mode.
“Twinkle twinkle little star i. myfile = open(‘student.txt’,’rb’)
How I wonder what you are ii. myfile = open(‘student.txt’,’w’)
Up above the world so high iii. myfile = open(‘student.txt’,’r’)
iv. myfile = open(‘student.txt’) line_count += 1
a. only i print(line_count)
b. both i and iv myfile.close()
c. both iii and iv a. 2
d. both i and ii b. 3
c. 4
[34] Suppose content of ‘Myfile.txt’ is d. 5
Humpty Dumpty sat on a wall
Humpty Dumpty had a great fall [38] Which of the following mode in the file opening
All the king’s horses and all the king’s men statement results or generates an error if the file does not
Couldn’t put Humpty together again exist?
What will be the output of the following code? (a) a+
myfile = open("Myfile.txt") (b) r+
record = myfile.read().split() (c) w+
print(len(record)) (d) None of the above
myfile.close()
a. 24 [39] The correct syntax of seek() is:
b. 25 (a) file_object.seek(offset [, reference_point])
c. 26 (b) seek(offset [, reference_point])
d. 27 (c) seek(offset, file_object)
(d) seek.file_object(offset)
[35] Suppose content of ‘Myfile.txt’ is
Honesty is the best policy. [40] Assertion (A): CSV (Comma Separated Values) is a file
What will be the output of the following code? format for data storage which looks like a text file.
Reason (R): The information is organized with one record
myfile = open("Myfile.txt") on each line and each field is separated by comma.
x = myfile.read() (a) Both A and R are true and R is the correct explanation
print(len(x)) for A
myfile.close() (b) Both A and R are true and R is not the correct
a. 5 explanation for A (c) A is True but R is False
b. 25 (d) A is false but R is True
c. 26
d. 27 [41] Consider the following directory structure:
computer science class 12 previous year questions
[36] Suppose the content of ‘Myfile.txt’ is : abosulute path
Culture is the widening of the mind and of the spirit. Suppose root directory (School) and present working
What will be the output of the following code? directory are the same. What will be the absolute path of
myfile = open("Myfile.txt") the file Syllabus.jpg?
x = myfile.read() a. School/syllabus.jpg
y = x.count('the') b. School/Academics/syllabus.jpg
print(y) c. School/Academics/../syllabus.jpg
myfile.close() d. School/Examination/syllabus.jpg
a. 2
b. 3 [42] Assume the content of the text file, ‘student.txt’ is:
c. 4 Arjun Kumar
d. 5 Ismail Khan
Joseph B
[37] Suppose the content of ‘Myfile.txt’ is : Hanika Kiran
Twinkle twinkle little star What will be the data type of data_rec?
How I wonder what you are myfile = open("Myfile.txt")
Up above the world so high data_rec = myfile.readlines()
Like a diamond in the sky myfile.close()
Twinkle twinkle little star a. string

What will be the output of the following code? b. list


myfile = open("MyFile.txt") c. tuple
line_count = 0 d. dictionary
data = myfile.readlines() [43] Which of the following option is not correct?
for line in data: a. if we try to read a text file that does not exist, an error
if line[0] == 'T': occurs.
b. if we try to read a text file that does not exist, the file If the content of the file is :
gets created. A BOY IS PLAYING OUTSIDE
c. if we try to write on a text file that does not exist, no THE PLAYGROUND IS BIG
error occurs. BANYAN TREE IS IN THE GROUND
d. if we try to write on a text file that does not exist, the The method/function should display:
file gets Created. A BOY IS PLAYING OUTSIDE
BANYAN TREE IS IN THE GROUND
[44] Which of the following options can be used to read Ans.:
the first line of a text file Myfile.txt? Steps:
a. myfile = open(‘Myfile.txt’); myfile.read() Method 1 Using starts with method
b. myfile = open(‘Myfile.txt’,’r’); myfile.read(n) Create a function using def as given in the question.
c. myfile = open(‘Myfile.txt’); myfile.readline() Create a file object myfile and open the file “lines.txt” in
d. myfile = open(‘Myfile.txt’); myfile.readlines() read (r) mode.
Declare an object d and store the contents of files in the
[45] Assume that the position of the file pointer is at the list using readlines() function.
beginning of 3rd line in a text file. Which of the following Traverse the list using for loop.
option can be used to read all the remaining lines? Now use the if condition to check the lines having the first
a. myfile.read() letter is either ‘A’ or ‘B’ using startswith() function.
b. myfile.read(n) Print the lines.
c. myfile.readline() Close the file.
d. myfile.readlines()
def ABLINES():
2 marks questions file handling class 12 computer myfile = open("lines.txt",'r')
science. d=myfile.readlines()
for i in d:
[1] Write a statement in Python to open a text file if i[0].startswith('A') or i[0].startswith('B'):
MARKER.TXT so that existing content can be read from it. print(i,end='')
Ans.: myfile.close()
Steps:
Create a file object/handle f to open the file “marker.txt” Method 2 Using index 0
in read mode using the open() function. Steps:
Create an object data and store the data using the read() Create a function ABLINES() starting with def keyword.
function. Create an object myfile to open “MyFile.txt” in read (r)
Print the data stored in the data object using the print() mode.
function. Create an object d to store the lines of the text file using
Close the file using the close() function. readlines() function.
Code: Traverse the list using for loop.
f=open("MARKER.txt") Use if condition to print the lines starts with ‘A’ or ‘B’
data=f.read() using the initial index 0.
print(data) Print the lines.
f.close() Close the file.

[2] Write a statement in Python to open a text file def ABLINES():


DATA.TXT so that new content can be written in it. myfile = open("MyFile.txt",'r')
Ans.: d=myfile.readlines()
Steps: for i in d:
Create a file object/handle f to open the file “data.txt” in if i[0]=='A' or i[0]=='B':
w (write) mode using the open() function. print(i,end='')
Use write () function to add new content to the file. myfile.close()
Close the file using the close() function.
Code: [4] Write a method/function SHORTWORDS( ) in python
f=open("DATA.TXT","w") to read lines from a text file WORDBANK.TXT, and display
f.write("Data file is ready to get data.") those words, which are lesser than 5 characters.
f.close() For example :
If the content of the file is :
[3] Write a method/function ABLINES( ) in python to read HAPPY JOY WELCOME KITE
contents from a text file LINES.TXT, to display those lines, LOVELY POSITIVE FUN
which is starting with either the alphabet ‘A’ or alphabet The method /function should display :
‘B’. JOY
For example: KITE
FUN wp = open("WriteUP.txt",'r')
Ans.: d=wp.read()
Steps: w=d.split()
Create a function SHORTWODS() starting with the def c=0
keyword. for i in w:
Create a file object wb and open the file “wordbank.txt” if 'tower' in i.lower():
in read (r) mode. c+=1
Now declare object d to store the contents of the file print("Tower word occurs:",c, " times in the file.")
using read() function. wp.close()
Declare a variable w to store the data received from the
file into a d object to split in words using split() function. [7] Write a function in python to count the number of
Traverse the words list object w using for loop. lines in a text file ‘STORY.TXT’ which is starting with an
Use if condition to print the words having less than 5 alphabet ‘A’ .
characters using relation operator < and len() function. Ans.:
Close the file. def begins_A():
f = open("Story.txt",'r')
.def SHORTWORDS(): d=f.readlines()
wb = open("wordbank.txt",'r') c=0
d=wb.read() for i in d:
w=d.split() if i[0]=='A':
for i in w: c+=1
if len(i)<5: print("The file story.txt contains", c," lines starting with
print(i) A.")
wb.close() f.close()
SHORTWORDS() [8] Write a method/function DISPLAYWORDS() in python
to read lines from a text file STORY.TXT, and display those
[5] Differentiate between the following : words, which are less than 4 characters.
f = open(‘diary.txt’, ‘a’) Ans.:
f = open(‘diary.txt’, ‘w’) def DISPLAYWORDS():
Ans.: f = open("STORY.txt",'r')
f = open(‘diary.txt’, ‘a’) f = open(‘diary.txt’, ‘w’) d=f.read()
This line opens a file for appending or adding content to w=d.split()
the text file diary.txt. for i in w:
This line opens a file for writing content to the text file if len(i)<4:
diary. txt. print(i,end=' ')
It will add the content to the end of the file. f.close()
It will overwrite the contents of the file.
For example: [9] Write a method in python to read the content from a
f=open(“dairy.txt”,’a’) text file story.txt line by line and display the same on
f.write(“New line added.”) screen.
f.close() For example: Ans.:
f=open(“dairy.txt”,’w’) def read_lines():
f.write(“Text file is created.”) f = open("story.txt",'r')
f.close() d=f.readlines()
for i in d:
[6] Write a method in python to read the Write function print(i,end='')
definition for TOWER( ) in python to read the content of a f.close()
text file WRITEUP.TXT, count the presence of word
TOWER and display the number of occurrences of this [10] Write a method in Python to read lines from a text
word. file INDIA.TXT, to find and display the occurrence of the
Note : – The word TOWER should be an independent word ‘‘India’’.
word – Ignore type cases (i.e. lower/upper case) For example :
Example : If the content of the file is
If the content of the file WRITEUP.TXT is as follwos : ‘‘India is the fastest growing economy. India is looking for
Tower of hanoi is an interesting problem. Mobile phone more investments around the globe. The whole world is
tower is away from here. Views from EIFFEL TOWER are looking at India as a great market. Most of the Indians can
amazing. foresee the heights that India is capable of reaching.“
The function TOWER( ) should display : 3 The output should be 4.
Ans.: Ans.:
def TOWER(): def india_freq():
myfile = open("india.txt",'r') print(i,end='')
d=myfile.read() myfile.close()
w=d.split()
c=0 [15] A text file named SOLUTION.TXT contains some
for i in w: English sentences. Another text file named TEST.TXT
if i.lower()=='india': needs to be created such that it replaces every
c+=1 occurrence of 3 consecutive letters ‘h’, ‘i’ and ‘s’
print("India found",c, " times.") (irrespective of their cases) from each word of the file
myfile.close() SOLUTION.TXT, with 3 underscores (‘___’).
For example :
[11] Write a statement in Python to open a text file If the file SOLUTION.TXT contains the following content :
WRITEUP.TXT so that new content can be written in it. “This is his history book.”
Refer answer 1. Then TEST.TXT should contain the following : “T ___ is ___
___tory book.”
[12] Write a statement in Python to open a text file Write the definition for function CreateTest()in Python
README.TXT so that existing content can be read from it. that would perform the above task of creating TEST.TXT
from the already existing file SOLUTION.TXT.
Refer answer 2. Ans.:
def Create_Test():
[13] Write a method/function ISTOUPCOUNT() in python myfile = open("solution.txt",'r')
to read contents from a text file WRITER.TXT, to count d=myfile.read()
and display the occurrence of the word ‘‘IS’’ or ‘‘TO’’ or t=d.replace('his','___')
‘‘UP’’. myfile = open("Test.txt",'w')
For example : myfile.write(t)
If the content of the file is – myfile.close()
IT IS UP TO US TO TAKE CARE OF OUR SURROUNDING. IT myfile = open("Test.txt",'r')
IS NOT POSSIBLE ONLY FOR THE GOVERNMENT TO TAKE print(myfile.read())
RESPONSIBILITY
The method/function should display [16] A text file named AGENCIES.TXT contains some text.
Count of IS TO and UP is 6 Write the definition for a function Showsites() in Python
Ans.: which displays all such words of the file which have more
than 9 characters and start with “www.”.
def istoupcount(): For example :
myfile = open("writer.txt",'r') If the file AGENCIES.TXT contains :
d=myfile.read() “Name: TechnoCraft, Website: www.technocraft.com,
w=d.split() Name: DataTech, Website: www.datatech.com”
c=0 Then the function Showsites() should display the output
for i in w: as : www.technocraft.com
if i.lower()=='is' or i.lower()=='up' or i.lower()=='to': www.datatech.com
c+=1 Ans.:
print("Count of is, up and to is:",c) def ShowSites():
myfile.close() f=open("Agencies.txt")
[14] Write a method/function AEDISP() in python to read data=f.read()
lines from a text file WRITER.TXT, and display those lines, words=data.split()
which are starting either with A or starting with E. for i in words:
For example : if len(i)>9 and i.startswith('www'):
If the content of the file is print(i)
A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD
HEALTH. WE SHOULD TAKE CARE OF OUR ENVIRONMENT. Computer Science Class 12 Data file handling 3 marks
EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD. questions
The method should display [1] Write a function in Python that counts the number of
A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD “Me” or “My” words present in a text file “STORY.TXT”.
HEALTH. If the “STORY.TXT” contents are as follows:
EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD. My first book was Me and My Family. It gave me chance
Ans.: to be Known to the world.
def AEDISP(): The output of the function should be:
myfile = open("writer.txt",'r') Count of Me/My in file: 4
d=myfile.readlines() def CountMyorMy():
for i in d: f=open("story.txt")
if i[0]=='A' or i[0]=='E': data=f.read()
words=data.split()
c=0 Today is a pleasant day. It might rain today. It is
for i in words: mentioned on weather sites
if 'Me' in i or 'My' in i:
c+=1 The ETCount() function should display the output as:
print("Count of Me/My in file:",c)
E or e: 6
[2] Write a function AMCount() in Python, which should
read each character of a text file STORY.TXT, which should T or t : 9
count and display the occurrence of alphabets A and M
(including small cases a and m too). Ans.:
Example: def ETCount():
If the file content is as follows: f = open("testfile.txt",'r')
Updated information As simplified by official websites. d=f.read()
The AMCount() function should display the output as: ec=0
A or a:4 tc=0
M or m :2 for i in d:
Ans.: if i.lower()=='e':
def AMCount(): ec+=1
f=open("story.txt") if i.lower()=='t':
data=f.read() tc+=1
ca=cm=0 print("E or e:",ec)
for i in data: print("T or t:",tc)
if 'a' in i.lower(): f.close()
ca+=1 ETCount()
if 'm' in i.lower():
cm+=1 [5] Aman is a Python programmer. He has written a code
print("A or a:",ca) and created a binary file record.dat with employeeid,
print("M or m:",cm) ename and salary. The file contains 10 records.
He now has to update a record based on the employee id
[3] Write a method COUNTLINES() in Python to read lines entered by the user and update the salary. The updated
from text file ‘TESTFILE.TXT’ and display the lines which record is then to be written in the file temp.dat. The
are not starting with any vowel. records which are not to be updated also have to be
Example: written to the file temp.dat. If the employee id is not
If the file content is as follows: found, an appropriate message should to be displayed.
An apple a day keeps the doctor away. We all pray for As a Python expert, help him to complete the following
everyone’s safety. A marked difference will come in our code based on the requirement given above:
country. import _______ #Statement 1
The COUNTLINES() function should display the output as: def update_data():
The number of lines not starting with any vowel – 1 rec={}
Ans.: fin=open("record.dat","rb")
def COUNTLINES(): fout=open("_____________") #Statement 2
f = open("testfile.txt",'r') found=False
d=f.readlines() eid=int(input("Enter employee id to update their
c=0 salary :: "))
for i in d: while True:
if i not in 'AEIOUaeiou': try:
c+=1 rec=______________ #Statement 3
print("The number of lines not starting with any vowel - if rec["Employee id"]==eid:
",c) found=True
f.close() rec["Salary"]=int(input("Enter new salary ::
"))
[4] Write a function ETCount() in Python, which should pickle.____________ #Statement 4
read each character of a text file “TESTFILE.TXT” and then else:
count and display the count of occurrence of alphabets E pickle.dump(rec,fout)
and T individually (including small cases e and t too). except:
break
Example: if found==True :
print("The salary of employee id ",eid," has been
If the file content is as follows: updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
Which module should be imported in the program?
(Statement 1)
Write the correct statement required to open a
temporary file named temp.dat. (Statement 2)
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?
Ans.:
pickle
open(“temp.dat”,”wb”)
pickle.load(fin)
pickle.dump(rec,fout)

5 Marks Questions File Handling Class 12 Computer


Science
[1] Ranjan Kumar of class 12 is writing a program to create
a CSV file “user.csv” which will contain user name and
password for some entries. He has written the following
code. As a programmer, help him to successfully execute
the given task.
import _____________ # Line 1
def addCsvFile(UserName,PassWord): # to write / add
data into the CSV file
f=open(' user.csv','________') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close() print("No. of books:",CountRec(a))
#csv file reading code [3] A binary file “STUDENT.DAT” has a structure
def readCsvFile(): # to read data from CSV file (admission_number, Name, Percentage). Write a function
with open(' user.csv','r') as newFile: countrec() in Python that would read contents of the file
newFileReader = csv._________(newFile) # Line 3 “STUDENT.DAT” and display the details of those students
for row in newFileReader: whose percentage is above 75. Also, display the number
print (row[0],row[1]) of students scoring above 75%.
newFile.______________ # Line 4 import pickle
addCsvFile(“Arjun”,”123@456”) def countrec():
addCsvFile(“Arunima”,”aru@nima”) f=open("student.dat","rb")
addCsvFile(“Frieda”,”myname@FRD”) c=0
readCsvFile() #Line 5 while True:
(a) Name the module he should import in Line 1. try:
(b) In which mode, Ranjan should open the file to add rec=pickle.load(f)
data into the file if rec[2]>75:
(c) Fill in the blank in Line 3 to read the data from a csv print(rec[0],rec[1],rec[2])
file. c+=1
(d) Fill in the blank in Line 4 to close the file. except EOFError:
(e) Write the output he will obtain while executing Line 5. break
f.close()
Ans.: [4] What is the advantage of using a csv file for
(a) csv permanent storage? Write a Program in Python that
(b) w mode defines and calls the following user-defined functions:
(c) reader()
(d) close() (i) ADD() – To accept and add data of an employee to a
(e) Frieda myname@FRD CSV file ‘record.csv’. Each record consists of a list with
field elements such as empid, name, mobile, and
[2] A binary file “Book.dat” has structure [BookNo, employee salary respectively.
Book_Name, Author, Price]. (ii) COUNTR() – To count the number of records present in
i. Write a user-defined function CreateFile() to input data the CSV file named ‘record.csv’.
for a record and add it to Book.dat. Ans.:
ii. Write a function CountRec(Author) in Python which The advantages of using a CSV file for permanent storage
accepts the Author name as a parameter and count and are as follows:
return the number of books by the given Author stored in It is a common file format used to store tabular data
the binary file “Book.dat”. It is human readable and easy to modify
Ans.: It is very simple to implement and parse data
import pickle It can be opened by general-purpose software like
def CreateFile(): notepad, MS Word, MS Excel
f=open("book.dat","ab") It is compact and faster to handle as well as small in size
book_no=int(input("Enter Book No.:")) import csv
book_name=input("Enter Book Name:") def ADD():
author=input("Enter author name:") f=open("record.csv","a",newline='')
price=float(input("Enter Price:")) emp_id=int(input("Enter employee id:"))
l=[book_no,book_name,author,price] ename=input("Enter Name:")
pickle.dump(l,f) mo=input("Enter Mobile No.:")
f.close() sal=int(input("Enter Salary:"))
def CountRec(Author): l=[emp_id,ename,mo,sal]
c=0 w=csv.writer(f)
f=open("book.dat","rb") w.writerow(l)
while True: f.close()
try:
rec=pickle.load(f) def COUNTR():
if rec[2]==Author: f=open("record.csv","r",newline='')
c+=1 r=csv.reader(f)
except EOFError: c=-1
break for i in r:
f.close() c+=1
return c print("No. of records in CSV are:",c)
CreateFile() f.close()
a=input("Enter author to search:")
[5] Give any one point of difference between a binary file Class = input("Enter Class : ")
and a csv file. Write a Program in Python that defines and section = input("Enter Section : ")
calls the following user defined functions: rec = [ _____ ] #Statement-4
(i) add() – To accept and add data of an employee to a data.append(_____) #Statement-5
CSV file ‘furdata.csv’. Each record consists of a list with stuwriter. _____ (data) #Statement-6
field elements as fid, fname and fprice to store furniture fh.close()
id, furniture name and furniture price respectively. i. Identify the suitable code for blank space in the line
marked as Statement-1.
(ii) search()- To display the records of the furniture whose a) csv file
price is more than 10000. b) CSV
Ans.: c) csv
Binary files process the data faster than CSV file. d) cvs
Binary files can’t be read by any software by the user Ans.: c) csv
directly, CSV data can be read by notepad, MS Word or
MS Excel. ii. Identify the missing code for blank space in line marked
The endline character or EndOfFile pointer is not present as Statement-2.
in binary file, the default endline character is /n.
import csv a) “Student.csv”,”wb”
def ADD():
f=open("furniture.csv","a",newline='') b) “Student.csv”,”w”
fid=int(input("Enter Furniture ID:"))
fname=input("Enter Furniture Name:") c) “Student.csv”,”r”
pri=int(input("Enter Price:"))
l=[fid,fname,pri] d) “Student.cvs”,”r”
w=csv.writer(f)
w.writerow(l) Ans.: b) “Students.csv”,”w”
f.close()
iii. Choose the function name (with argument) that should
def search(): be used in the blank space of the line marked as
f=open("furniture.csv","r",newline='') Statement-3.
r=csv.reader(f)
for i in r: a) reader(fh)
if int(i[2])>10000:
print(i) b) reader(MyFile)
f.close()
c) writer(fh)
[6] Rohit, a student of class 12, is learning CSV File Module
in Python. During examination, he has been assigned an d) writer(MyFile)
incomplete python code (shown below) to create a CSV
File ‘Student.csv’ (content shown below). Help him in Ans.: c) writer(fh)
completing the code which creates the desired CSV File.
iv. Identify the suitable code for blank space in line
CSV File marked as Statement-4.
1,AKSHAY,XII, A a) ‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’
2,ABHISHEK,XII, A b) ROLL_NO, NAME, CLASS, SECTION
3,ARVIND,XII, A c) ‘roll_no’,’name’,’Class’,’section’
4,RAVI,XII, A d) roll_no,name,Class,section

5,ASHISH,XII,A Ans.: d) roll_no,name,Class,section

Incomplete Code v. Identify the suitable code for blank space in the line
import _____ #Statement-1 marked as Statement-5.
fh = open(_____, _____, newline='') #Statement-2
stuwriter = csv._____ #Statement-3 a) data
data = [ ] b) record
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION'] c) rec
data.append(header) d) insert
for i in range(5): Ans.: c) rec
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
vi. Choose the function name that should be used in the Ans.: b) for R in ER:
blank space of line marked as Statement-6 to create the
desired CSV File? v) Identify the suitable code for blank space in Statement-
a) dump() 5 to match every row’s 3rd property with “ACCOUNTS”.
b) load()
c) writerows() a) ER[3]
d) writerow() b) ER[2]
Ans.: d) writerow() c) R[2]
d) R[3]
[7] Nisha, an intern in ABC Pvt. Ltd., is developing a
project using the csv module in Python. She has partially Ans.: c) R[2]
developed the code as follows leaving out statements vi) Identify the suitable code for blank space in Statement-
about which she is not very confident. The code also 6 to display every Employee’s Name and corresponding
contains errors in certain statements. Help her in Department?
completing the code to read the desired CSV File named a) ER[1], R[2]
“Employee.csv”. b) R[1], ER[2]
c) R[1], R[2]
#CSV File Content d) ER[1], ER[2]
ENO, NAME, DEPARTMENT Ans.: c) R[1], R[2]
E1,ROSHAN SHARMA , ACCOUNTS
E2,AASMA KHALID, PRODUCTION
E3,AMRIK GILL,MARKETING
E4,SARAH WILLIAMS, HUMAN RESOURCE
#incomplete Code with Errors
import CSV #Statement-1
with open (______,_______ newline='') as. File:
#Statement-2
ER= csv. ________ #Statement-3
for R in range (ER) #Statement-4
if __________=="ACCOUNTs" #Statement-5
print(________) #Statement-6
i) Nisha gets an Error for the module name used in
Statement-1. What should she write in place of CSV to
import the correct module ?
a) file
b) csv
c) Csv
d) pickle
Ans.: b) csv
ii) Identify the missing code for blank spaces in the line
marked as Statement-2 to open the mentioned file.
a) “Employee.csv”, “r”
b) “Employee.csv”, “w”
c) “Employee.csv”, “rb”
d) “Employee.csv”, “w”
Ans.: a) “Employee.csv”,”r”
iii) Choose the function name (with parameter) that
should be used in the line marked as Statement-3.

a) reader (File)
b) readrows (File)
c) writer (File)
d) writerows (File)
Ans.: a) reader(File)
iv) Nisha gets an Error in Statement-4. What should she
write to correct the statement?
a) while R in range (ER) :
b) for R in ER:
c) for R = ER:
d) while R = ER:

You might also like