DATA FILE HANDLING Chapter Clearance
DATA FILE HANDLING Chapter Clearance
Questions:
1. What is the function used to open a file in Python?
2. What is a file mode in Python?
3. What is the difference between write and append?
4. What is the default mode for opening a file in Python?
5. How do you read the entire content of a file in Python?
6. What is the difference between read() and readline() in file handling?
7. How do you write data to a file in Python?
8. What happens if you open a file in 'w' mode and the file already exists?
9. How do you append data to an existing file in Python?
10.What does the close() method do in file handling?
11.What is the use of the with statement in file handling?
12.How do you read a file line by line in Python?
13.What is the use of the readlines() method in file handling?
14.Differentiate between text file and binary file.
15.Differentiate between readline() and readlines().
16.Differentiate between write() and writelines().
17.Write the use and syntax for the following methods:
18.Write the file mode that will be used for opening the following files. Also, write the
Python statements to open the following files:
19.What is the difference between the following set of statements (a) and (b):
P = open("practice.txt", "r")
P.read(10)
with open("practice.txt", "r") as P:
x = P.read()
20.Write a command(s) to write the following lines to the text file named hello.txt.
Assume that the file is opened in append mode.
“ Welcome my class”
“It is a fun place”
“You will learn and play”
21.Differentiate between file modes r+ and w+ with respect to python.
22. What would be the data type of variable data in the following statements?
(a) data = f.read()
(b) data = f.read(10)
(c) data = f.readline()
(d) data = f.readlines()
(b) Modify the program so that the lines are printed in reverse order.
(c) Modify the code so as to output to another file instead of the screen. Let your script
overwrite the output file.
(d)Change the script of part (c) that it append output to an existing file.
(e) Modify the program so that each line is printed with a line number at beginning.
45. Following is the structure of each record in a data file named "PRODUCT.DAT".
("prod_code": value, "prod_desc": value, "stock": value)
The values for prod_code and prod_desc are strings and the value for stock is an integer.
46. Write a function in Python to update the file with a new value of stock. The stock and the
product_code, whose stock is to be updated, or to be inputted during the execution of the
function.
47. Write a program to read entire data from file data.csv.
48. Write a program to search the record from “data.csv” according to the admission number
input from the user. Structure of record saved in “data.csv” is ADM_no, Name, Class, Sec,
Marks.
49. Write a program to read all the content of “student.csv” and display records of only those
students who scored more than 80 marks. Records stored in studentsis in format: Rollno,
Name, Marks.
50. Write a program to display all the records from products.csv whose price is more than 300.
Format of record stored in product.csv is product id, product name, price.
51. Write a program to copy the data from “data.csv” to “temp.csv”.
52. Write a program to count the number of records present in “data.csv” file.
53. Arun, during Practical Examination of Computer Science, has been assigned an
incomplete search() function to search in a pickled file student.dat. The File student.dat is
created by his Teacher and the following information is known about the file. • File contains
details of students in [roll_no,name,marks] format.
• File contains details of 10 students (i.e. from roll_no 1 to 10) and separate list of each
student is written in the binary file using dump().
Arun has been assigned the task to complete the code and print details of roll number 1.
def search():
f = open("student.dat",____) #Statement-1
____: #Statement-2
while True:
rec = pickle.____ #Statement-3
if(____): #Statement-4
print(rec)
except:
pass
____ #Statement-5
3) Identify the function (with argument), to be used at blank space in line marked as
Statement-3.
a) load() b) load(student.dat) c) load(f) d) load(fin)
4) What will be the suitable code for blank space in line marked as Statement-4.
a) rec[0]==2 b) rec[1]==2 c) rec[2]==2 d) rec[0]==1
5) Which statement Arun should use at blank space in line marked as Statement4 to close the
file.
a) file.close() b) close(file) c) f.close() d) close()
54. Radha Shah is a programmer, who has recently been given a task to write a python code to
perform the following CSV file operations with the help of two user defined
functions/modules:
a. CSVOpen() : to create a CSV file called BOOKS.CSV in append mode containing
information of books – Title, Author and Price.
b. CSVRead() : to display the records from the CSV file called BOOKS.CSV where the field
title starts with 'R'.
She has succeeded in writing partial code and has missed out certain statements, so she has
left certain queries in comment lines.
import csv
def CSVOpen():
with open('books.csv','______',newline='') as csvf: #Statement-1
cw=______ #Statement-2
______ #Statement-3
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])
def CSVRead():
try:
with open('books.csv','r') as csvf:
cr=______ #Statement-4
for r in cr:
if ______: #Statement-5
print(r)
except:
print('File Not Found')
CSVOpen()
CSVRead()
You as an expert of Python have to provide the missing statements and other related queries
based on the following code of Radha. Answer any four questions (out of five) from the below
mentioned questions.
1) Choose the appropriate mode in which the file is to be opened in append mode (Stmt 1)
a. w+ b. ab c. r+ d. a
2) Which statement will be used to create a csv writer object in Statement 2.
a. csv.writer(csvf) b. csv.writer(csvf) c. csvf.writer() d. cs.writer(csvf)
3) Choose the correct option for Statement 3 to write the names of the column headings in the
CSV file, BOOKS.CSV.
a. cw.writerow('Title','Author','Price') b. cw.writerow(['Title','Author','Price'])
c. cw.writerows('Title','Author','Price') d. cw.writerows(['Title','Author','Price'])
4) Which statement will be used to read a csv file in Statement 4.
a. cs.read(csvf) b. csv.reader(csvf) c. csvf.read() d. csvf.reader(cs)
5) Fill in the appropriate statement to check the field Title starting with ‘R’ for Statement 5 in
the above program.
a. r[0][0]=='R' b. r[1][0]=='R' c. r[0][1]=='R d. d. r[1][1]=='R'
55. Create a CSV file "Groceries" to store information of different items existing in a shop.
The information is to be stored w.r.t. each item code, name, price, qty. Write a program to
accept the data from user and store it permanently in CSV file.
56. Write a single loop to display all the contents of a text file “sports.txt” after removing
leading and trailing whitespaces.
21. Every file has its own identity associated with it. Which is known as –
a. icon b. extension c. format d. file type
25. Which of the following file types allows to store large data files in the computer memory?
a. Text Files b. Binary Filesc. CSV Files d. None of these
26. Which of the following file types can be opened with notepad as well as ms excel?
a. Text Files b. Binary Files c. CSV Files d. None of these
28. To read 4th line from text file, which of the following statement is true?
a. dt = f.readlines();print(dt[3]) b. dt=f.read(4) ;print(dt[3])
c. dt=f.readline(4);print(dt[3]) d. All of these
30. Which of the following functions flushes the data before closing the file?
a. flush() b. close() c. open() d. fflush()
31. What is the output of the following code?
59. Write the output of the following, if the data stored in file “try.txt” is given below.
(“f” is the file object associated with file)
Try Try but never cry
print(f.read(4))
print(f.read(5))
print(f.read())
63. What are the two built-in functions to read a line of text from standard input, which is by default the
keyboard?
A. Raw_input B. Input C. Read D. Scanner
67. Which of the following will read entire content of file(file object ‘f’)?
a. f.reads( ) b. f.read( ) c. f.read(all) d. f.read( * )
69. Which of the following options can be used to read the first line of a text file data.txt?
a. f = open(‘data.txt’); f.read() b. f = open(‘data.txt’,’r’); f.read(n)
c. myfile = open(‘data.txt’); f.readline() d. f = open(‘data.txt’); f.readlines()
72. Which function is used to force transfer of data from buffer to file?
a. flush( ) b. save( ) c. move( ) d. None of the above
73. Let the file pointer is at the end of 3rd line in a text file named “data.txt”. Which of the following option
can be used to read all the remaining lines?
a. f.read( ) b. f.read(all) c. f.readline( ) d. f.readlines( )
74. ____________________ module is used for serializing and de-serializing any Python object structure.
a. pickle b. unpickle c. pandas d. math
75. Which of the following error is returned when we try to open a file in write mode which does not exist?
a. FileNotFoundError b. FileFoundError c. FileNotExistError d. None of the above
80. readlines( ) function returns all the words of the file in the form of List. (T/F)
a. True b. False
84. What error is returned by the following statement if the file does not exist?
f=open("A.txt")
a. FileNotFoundError b. NotFoundError
c. FileNotFound d. FoundError
87. Almost all the files in our computer stored as _______ File.
a. Text b. Binary c. CSV d. None of the above
89. Fill in the blanks in the following code of writing data in binary files. Choose the answer for statement 1
import ___________ # Statement 1
rec = [ ]
while True:
rn = int(input("Enter"))
nm = input("Enter")
temp = [rn, nm]
rec.append(temp)
ch = input("Enter choice (Y/N)")
if ch.upper == "N":
break
f = open("stud.dat", "____________") #statement 2
__________ .dump(rec, f) #statement 3
_______.close( ) # statement 4
90. Refer to the above code and choose the option for statement2.
a. w b. w+ c. wb d. write
91. Refer to the above code and choose the option for statement 3
a. unpickle b. write c. pickle d. None of the above
92. Refer to the above code and choose the option for statement 4.
a. f b. rec c. file d. stud
93. The syntax of seek() is:file_object.seek(offset [, reference_point] What is the default value of
reference_point
a. 0 b. 1 c. 2 d. 3
95. Which statement will move file pointer 10 bytes backward from current position.
a. f.seek(-10, 0) b. f.seek(10, 0) c. f.seek(-10, 1) d. None of the above
96. When we open file in append mode the file pointer is at the _________ of the file.
a. end b. beginning c. anywhere in between the file d. second line of the file
97. When we open file in write mode the file pointer is at the _______ of the file.
a. end b. beginning c. anywhere in between the file d. second line of the file
99. Refer to the above code: Write the output of Second Print Statement
a. om b. me c. co d. None of the above
100. Refer to the above code: Write the output of Third Print Statement
a. e to m b. e to my c. to my d. None of the above
101. Refer to the above code: Write the output of Fourth Print Statement
a. 17 b. 16 c. 19 d. 18
102. A _____________ is a named location on a secondary storage media where data are permanently stored
for later access.
a. file b. variable c. comment d. token
104. Which of the following file require specific programs to access its contents?
a. Binary b. Text c. CSV d. None of the above
105. Which of the following file can be opened in any text editor?
a. Binary b. Text c. Both of the above d. None of the above
106. Each line of a text file is terminated by a special character, called the ________
a. End of File b. End of Line c. End of Statement d. End of program
114. Which of the following attribute of file handle returns Boolean value?
a. name b. closed c. mode d. None of the above
115. Ravi opened a file in python using open( ) function but forgot to specify the mode. In which mode the
file will open?
a. write b. append c. read d. read and write both
117. Which of the following mode will opens the file in read, write and binary mode?
a. ‘wb+ b. ‘+wb’ c. Both of the above d. None of the above
118. In the given statement, the file myfile.txt will open in _______________ mode.
myObject=open(“myfile.txt”, “a+”)
a. append and read b. append and write c. append and read and binaryd. All of the above
119. Ravi opened the file myfile.txt in append mode. In this file the file object/file handle will be at
the __________
a. beginning of the file b. end of the file c. second line of the file d. the end of the
first line
120. Ravi opened the file myfile.txt in write mode. In this file the file object/file handle will be at
the ______________
a. beginning of the file b. end of the file c. second line of the file d. the end of the
first line
121. Ravi opened the file myfile.txt in read mode. In this file the file object/file handle will be at
the _______________
a. beginning of the file b. end of the file c. second line of the file d. the end of the
first line
122. Ravi opened a file in a certain mode. After opening the file, he forgot the mode. One interesting fact
about that mode is ” If the file already exists, all the contents will be overwritten”. Help him to identify the
correct mode.
a. read mode b. write mode c. append mode d. binary and read mode
123. Ram opened a file in a certain mode. After opening the file, he forgot the mode. The interesting facts
about that mode are ” If the file doesn’t exist, then a new file will be created” and “After opening file in that
mode the file handle will be at the end of the file” Help him to identify the correct mode.
a. read mode b. write mode c. append mode d. binary and read mode
126. Which of the following is the valid way to open the file?
a. with open (file_name, access_mode) as fo: b. fo = open (file_name, access_mode)
c. Both of the above d. None of the above
127. Rohan opened the file “myfile.txt” by using the following syntax. His friend told him few advantages of
the given syntax. Help him to identify the correct advantage.
with open ("myfile.txt", "a") as file_object:
a. In case the user forgets to close the file explicitly the file will closed automatically.
b. file handle will always be present in the beginning of the file even in append mode.
c. File will be processed faster d. None of the above
128. Mohan wants to open the file to add some more content in the already existing file. Suggest him the
suitable mode to open the file.
a. read mode b. append mode c. write mode d. All of the above
129. Aman jotted down few features of the “write mode”. Help him to identify the valid features.
a. If we open an already existing file in write mode, the previous data will be erased
b. In write mode, the file object will be positioned at the beginning of the file.
c. In write mode, if the file does not exist then the new file will be created.
d. All of the above
130. Ananya jotted down few features of the “append mode”. Help her to identify the valid features.
a. If we open an existing file in append mode, the previous data will remain there.
b. In append mode the file object will be positioned at the end of the file.
c. In append mode, if the file does not exist then the new file will be created.
d. All of the above
131. Which of the following methods can be used to write data in the file?
a. write( ) b. writelines( ) c. Both of the above d. None of the above
135. Which of the following method does not return the number of characters written in the file.
a. write( ) b. writelines( ) c. Both of the above d. None of the above
137. In order to read the content from the file, we can open file in ___________________
a. “r” mode b. “r+” mode c. “w+” mode d. All of the above
138. Which of the following method is used to read a specified number of bytes of data from a data file.
a. read( ) b. read(n) c. readlines( ) d. reading(n)
147. Select the correct statement about the code given below:
>>> myobj=open("myfile.txt", 'r')
>>> print(myobj.readlines())
a. This code will read one line from the file. b. This code will read all the lines from the file.
c. This code will read only last line from the file. d. None of the above
149. Which of the following function return the data of the file in the form of list?
a. read( ) b. read(n) c. readline( ) d. readlines( )
150. Sanjeev has written a program which is showing an error. As a friend of Sanjeev, help him to identify the
wrong statement.
f=open("test.txt","w") #Statement1
L = ["My name\n", "is\n", "Amit"] #Statement2
f.writeline(L) #Statement3
f.close() #Statement4
a. Statement1 b. Statement2 c. Statement3 d. Statement4
151. ____________________ function returns an integer that specifies the current position of the file object in
the file.
a. seek( ) b. tell( ) c. disp( ) d. None of the above
152. _______ method is used to position the file object at a particular position in a file.
a. tell( ) b. seek( ) c. put( ) d. None of the above
153. In reference to the code given below, the file object will move _______ bytes.
file_object.seek(10, 0)
a. 0 b. 10 c. 5 d. 4
154. Ravi wants to move the file object 5 bytes from the current position of the file object. As a friend of
Ravi, help him to write the code.
a. file_object.seek(5, 1) b. file_object.seek(1, 5)
c. file_object.seek(5, 0) d. file_object.seek(5, 2)
163. Which of the following statement open the file “marker.txt” so that we can read existing content from
file?
a. f = open(“marker.txt”, “r”) b. f = Open(“marker.txt”, “r”)
c. f = open(“marker.txt”, “w”) d. None of the above
164. Which of the following statement open the file “marker.txt” as a blank file?
a. f = open(“marker.txt”, “r”) b. f = open(“marker.txt”, “rb”)
c. f = open(“marker.txt”, “w”) d. None of the above
165. Amit has written the following statement. He is working with ______
f = open("data", "rb")
a. Text File b. CSV File c. Binary File d. None of the above
170. Identify the statement which can not be interpret from the given code:
f = open("test.dat", "ab+")
a. test.dat is a binary file b. reading operation can be done on test.dat
c. appending operation can be done on test.dat d. test.dat contains records about books
174. Write the output of the second print statement of the given code:
f=open("test.txt","r")
print(f.read())
f.seek(7)
print(f.read())
Output of first print statement is : MynameisAmit
a. isAmit b. sAmit c. Amit d. eisAmit
176. ___________ refers to the process of converting the structure to a byte stream before writing it to the
file.
a. pickling b. unpickling c. reading d. writing
183. Ravi is writing a program for counting the number of words in a text file named “data.txt”. He has
written the incomplete code. Help him to complete the code.
f = open("_________","r") # Statement 1
d = f._________ # Statement 2
nw = d._________ # Statement 3
print("Number of words are", _________(nw)) # Statement 4
184. Identify the suitable code for blank space in the line marked as Statement 1
a. “data.txt” b. data.txt c. “data” d. data
185. Identify the suitable code for blank space in the line marked as Statement 2(Refer Q. 137)
a. readlines( ) b. readline( ) c. read( ) d. None of the above
186. Identify the suitable code for blank space in the line marked as Statement 3(Refer Q. 137)
a. split( ) b. break( ) c. words( ) d. jump( )
187. Identify the suitable code for blank space in the line marked as Statement 4(Refer Q. 137)
a. length b. len c. Len d. Length
188. Ananya was writing a program of reading data from csv file named “data.csv”. She writes the incomplete
code. As a friend of Ananya help her to complete the code.
________ csv #Statement1
f=open("data.csv", '_______') #Statement2
d=csv.___________(f) #Statement3
for __________ in d: #Statement4
print(row)
Identify the suitable option for Statement 1
a. import b. create c. data d. Import
192. Parth is writing a program to add/insert records in file “data.csv”. He has written the following code. As
a programmer, help him to execute it successfully.
import csv
field = [“Roll no” , “Name” , “Class”]
f = open(“_________” , ‘w’) #Statement1
d=__________.writer(f) #Statement2
d.writerow(field)
ch=’y’
while ch==’y’ or ch==’Y’:
rn=int(input(“Enter Roll number: “))
nm = input(“Enter name: “)
cls = input(“Enter Class: “)
rec=[_________] #Statement3
d.writerow(rec)
ch=input(“Enter more record??(Y/N)”)
f.close()
195. Chinki is writing a program to copy the data from “data.csv” to “temp.csv”. However she is getting some
error in executing the following program due to some missing commands. Help her to execute it successfully.
import csv
f=open(“data.csv”,”r”)
f1=open(“temp.csv”,’__________’) #Statement 1
d=csv._________(f) #Statement 2
d1=csv.writer(f1)
for i in d:
___________.writerow(i) #Statement3
f.close( )
f1.close( )
198. Simran is writing a function by name “bookshop” in which she is asking about book name and price
from the user and storing the details in a file “book.txt”. Function is showing some error due to some missing
words/commands. As a programmer help her to write the correct program.