CSV FILE
1. (i) Differentiate between the writerow and writerows function.
(ii) Write a Program in Python that defines and calls the
following user definedfunctions:
(i) add() – To accept and add data of an employee to a CSV
file„ EMP.CSV‟. Each record consists of a list with
field elementsas EId, EName and ESal to store
Emp id, Empname andfurniture price respectively.
(ii) search()- To display the records of the furniture whose
price is morethan 10000
Ans:
import csv
def Add():
f = open('EMP.CSV','w', newline ='')
w = csv.writer(f)
header = ['EId', 'EName', 'ESal']
w.writerow(header)
ans ='y'
while ans.lower() == 'y':
EId=int(input('Enter EId: '))
EName=input('Enter EName: ')
ESal=int(input('Enter Furniture Price: '))
rec=[EId, EName, ESal]
ans = input('continue ? (y/n): ')
w.writerow(rec)
f.close()
Add()
def Search():
f = open('EMP.CSV', newline = '')
records = csv.reader(f, delimiter =',')
#c =0
for line in records:
#print(line)
if line[2] == 'ESal' :
pass
elif int(line[2]) > 1000:
#c+=1
print(line)
f.close()
Search()
2. Help Sumit to find theanswer of the following questions to
find the correct code for missing statements.
#Incomplete Code
import_________________________ #Statement 1
fh = open( _____ ,____ , newline=" ") #Statement 2
stuwriter = csv _________________ #Statement 3
data = []
header = [„ ROLL_NO‟, „ NAME‟, „ CLASS‟, „ SECTION‟]
data.append(header)
for i in range(5):
roll_no = int(input(“Enter Roll Number : ”))
name = input(“Enter Name : ”)
Class = input(“Class : ”)
section = input(“Enter Section : ”)
rec = [_________] #Statement 4
data.append(rec)
stuwriter._____________(data) #Statement 5
fh.close()
(i) Identify the suitable code for blank space in line marked
as Statement 1.
(ii) Identify the missing code for blank space in line
marked as Statement 2.
(iii) Choose the function name (with argument) that should
be used in the blank space of line marked as
Statement 3.
(iv) Identify the suitable code for blank space in line
marked as Statement 4.
(v) Choose the function name that should be used in the
blank space of line marked as Statement 5 to create the
desired CSV file?
Ans:
(i) import csv # Statement 1
(ii) fh = open('file.csv','w') # Statement 2
(iii) stuwriter = csv.writer(fn) # Statement 3
(iv) rec =[roll_no,name,class,section] # Statement 4
(v) stuwriter.writerow(data)
3. (a) What is the use of seek() function ? Write a python
program that defines and calls the following user
defined functions.
(b) Add_book() – To read the details of the books from the
user and write into the csv file named “book.csv”.
The details of the books stored
in a list are book_no,name,author.
Search_book() - To read the author name from the user
and display the books written by the
author.
Ans:
import csv
def Add_book():
f = open('Book.csv','w', newline ='')
w = csv.writer(f)
header = ['BookNo', 'Book_Name', 'Author']
w.writerow(header)
ans ='y'
while ans.lower() == 'y':
b_no=int(input('Enter Book number: '))
b_name=input('Enter Book Name: ')
author_name=input('Enter Author Name: ')
rec=[b_no, b_name, author_name]
ans = input('continue ? (y/n): ')
w.writerow(rec)
f.close()
Add_book()
def Search_book(Author):
f = open('Book.csv', newline = '')
records = csv.reader(f, delimiter =',')
c =0
for line in records:
print(line)
if line[2] == 'Author':
pass
elif line[2] == Author:
c+=1
#print(line)
print('Number of books by the given Author : ' , c)
f.close()
Author=input('Enter Author Name to search: ')
Search_book(Author)
(or)
import csv
def Add_book():
f = open('Book.csv','w', newline ='')
w = csv.writer(f,delimiter =',')
header = ['BookNo', 'Book_Name', 'Author']
w.writerow(header)
rec =[]
ans ='y'
while ans.lower() == 'y':
b_no=int(input('Enter Book number: '))
b_name=input('Enter Book Name: ')
author_name=input('Enter Author Name: ')
rec.append([b_no, b_name, author_name])
ans = input('continue ? (y/n): ')
w.writerows(rec)
f.close()
Add_book()
def Search_book(Author):
f = open('Book.csv', newline = '')
records = csv.reader(f, delimiter =',')
c =0
for line in records:
print(line)
if line[2] == 'Author':
pass
elif line[2] == Author:
c+=1
#print(line)
print('Number of books by the given Author : ' , c)
f.close()
Author=input('Enter Author Name to search: ')
Search_book(Author)
4. (a) How to open the file using with statement? Write a
python program that defines and calls the user defined
functions given below.
(b) Add_rating() – To read product name and rating from
the user and store the same into the
csv file “product.csv”
Display() – To read the file “product.csv” and display
the products where the rating is above 10
Ans:
import csv
def Add_rating():
f = open('product.csv','w', newline ='')
w = csv.writer(f)
header = ['Product_Name', 'Rating']
w.writerow(header)
ans ='y'
while ans.lower() == 'y':
Product_Name=input('Enter Product_Name: ')
Rating=int(input('Enter Rating: '))
rec=[Product_Name, Rating]
ans = input('continue ? (y/n): ')
w.writerow(rec)
f.close()
Add_rating()
def Display():
f = open('product.csv', newline = '')
records = csv.reader(f, delimiter =',')
#c =0
for line in records:
#print(line)
if line[1] == 'Rating':
pass
elif int(line[1]) > 10:
#c+=1
print(line[0])
f.close()
Display()
5. Write a program in python that defines and calls the
following user defined functions:
(i) insertData() – To accept and add data of a customer and
add it to a csv file 'customerData.csv‟.
Each record should contain a list
consisting customer name, mobile no,
date of Purchase, item purchased.
(ii) frequency (name) – To accept the name of a customer
and search how many times the customer
has purchased any item. The count
and return the number.
Ans:
import csv
def insertData():
f = open('customerData.csv','w', newline ='')
w = csv.writer(f)
header = ['customer_name', 'mobile_no', 'date_of_Purchase', 'item_purchased']
w.writerow(header)
ans ='y'
while ans.lower() == 'y':
customer_name=input('Enter customer_name: ')
mobile_no=int(input('Enter mobile_no: '))
date_of_Purchase=input('Enter date_of_Purchase: ')
item_purchased=input('Enter item_purchased: ')
rec=[customer_name, mobile_no, date_of_Purchase, item_purchased]
ans = input('continue ? (y/n): ')
w.writerow(rec)
f.close()
insertData()
def Display(customer_name):
f = open('customerData.csv', newline = '')
records = csv.reader(f, delimiter =',')
c =0
for line in records:
# print(line)
if line[0] == 'customer_name':
pass
elif line[0] == customer_name:
c+=1
#print(line[0])
print('Number of times the customer has purchased : ' , c)
f.close()
customer_name=input('Enter customer_name to display details: ')
Display(customer_name)
6. Arun is a class XII student of computer science. The CCA
in-charge of his school wants to display the words form a
text files which are less than 4 characters. Do the needful
with the following python code.
def FindWords():
c=0
file=open("NewsLetter.TXT", "____ ") #Statement-1
line = file.____________ #Statement-2
word =______________ #Statement-3
for c in word:
if _____________: #Statement-4
print(c)
________________#Statement-5
FindWords()
(i) Write mode of opening the file in statement-1?
(ii) Fill in the blank in statement-2 to read the data from the file.
(iii) Fill in the blank in statement-3 to read data word by word.
(iv) Fill in the blank in statement-4, which display the word
having lesser than 4 characters.
(v) Fill in the blank in Statement-5 to close the file.
(vi) Which method of text file will read only one line of the file?
Ans:
(i) file = open("NewsLetter.TXT","r") # Statement -1
(ii) line = file.read() # Statement-2
(iii) word = file.split() # Statement -3
(iv) if len(c)<4: # Statement-4
(v) file.close() # Statement-5
(vi) readline()
7. Anu got some errors while executing the program so she
deleted those lines. As a python programmer guide her to
fill the missing statements.
_____________ # Statement 1
def modify():
e=[ ]
____________ # Statement 2
found=False
T_eno=int(input("enter employee no"))
try:
while True:
____________ # Statement 3
e=pickle.load(f)
if e[0] == T_eno:
e[2]=float(input("enter new salary"))
f.seek(pos)
__________ # Statement 4
found=True
except:
f.close()
if found==True:
print("employee record found and updated")
else:
print("employee record not found and updating not
possible")
(i) Write the statement to import the needed module.
(ii) Write the statement to open the file named “emp.bin” as
per the need of the code.
(iii) Write the statement to store the position of the file
pointer.
(iv) Complete the blank with the statement to write the
object “e” into the file
Ans:
(i) import pickle # Statement 1
(ii) f = open('emp.bin','rb') # Statement 2
(iii) pos = f.tell() # Statement 3
(iv) pickle.dump(e,f) # Statement 4
8. Ariba Malik has been following incomplete code, which
takes a student‟s details (rollnumber, name and marks)
and writes into a binary file stu.dat using pickling.
import pickle
sturno=int(input(“Enter roll number:”))
stuname=input(“Enter name:”)
stumarks=float(input(“Enter marks:”))
stu1={"RollNo.":sturno,"Name":stuname,"Marks":stumarks}
with __________ as fh: # Fill_Line1
________________ # Fill_Line2
______________ as fin: # Fill_Line3
________________ # Fill_Line4
print(Rstu)
if Rstu[“Marks”]>=85:
print(“Eligible for merit certificate”)
else:
print(“Not eligible for merit certificate”)
(a) Complete Fill_Line1 so that the mentioned binary file is
opened for writing in fh object using a with statement.
(b) Complete Fill_Line2 so that the dictionary stu1‟s
contents are written on the file opened in step(a)
(c) Complete Fill_line3 so that the earlier created binary file
is opened for reading in a file object namely fin, using a
with statement.
(d) Complete Fill_line4 so that the contents of open file in
fin are read into a dictionary namely Rstu.
Ans:
(a) with open("stu.dat","wb") as fh: # Fill_Line1
(b) pickle.dump(stu1,fh) # Fill_Line2
(c) with open("stu.dat","rb") as fin: # Fill_Line3
(d) Rstu = pickle.load(fin) # Fill_Line4
9. Ahana is writing a program to create a binary file
Employee.dat which will contain Empcode and Salary for
some employees. She has written the following code. As a
programmer, help her to successfully execute the given
task (i) Name the module she should import in Line1.
(ii) In which mode, she should open the file in Line2 to add
data into the file.
(iii) Fill in the blank in Line3 to read data from the binary file.
(iv) Write the output she will obtain while executing Line4.
Ans:
(i) import pickle as p # Line1
(ii) f = open("Employee.dat","wb") # Line2
(iii) record= p.load(f) # Line3
(iv) Anaga 30000
Neha 70000
10. Aaruni Shah is learning to work with Binary files in python
using a process known as pickling/de-pickling. Her
teacher has given her the following incomplete code, which
is creating a binary file namely Mydata.dat and then opens
, reads and displays the content of the created files.
________________ #Fill_Line 1
sqlist = list()
for k in range(10):
sqlist.append(k*k)
fout = ______________ #Fill_Line2A
____________________ #Fill_Line3
fout.close()
fin = __________________ #Fill_Line2B
______________________ #Fill_Line4
fin.close()
print(“Data from file:”,mylist)
Help her complete the above code as per the instructions
given below:
(a) Complete Fill_Line1 so that the required Python library
becomes available to the program.
(b) Complete Fill_Line2A so that the above mentioned
binary file is opened for writing in the file object fout.
Similarly, complete Fill_Line2B, which will open the
same binary file for reading in the file object fin.
(c) Complete Fill_Line3 so that the list created in the code,
namely Sqlist is written in the open file.
(d) Complete Fill_Line4 so that the contents of the open file
in the file handle fin are read in a list namely mylist.
Ans:
(a) import pickle #Fill_Line 1
(b) fout = open("Mydata.dat","wb") #Fill_Line 2A
fin = open("Mydata.dat","rb") #Fill_Line 2B
(c) pickle.dump(sqlist,fout) #Fill_Line 3
(d) mylist = pickle.load(fin) #Fill_Line 4
11. import pickle
sturno = int(input("Enter roll number :"))
stuname = input("Enter name:")
stumarks = float(input("Enter marks :"))
Stul = {"RNo. ":sturno, "Name": name, "Marks":stumarks}
with ______________________ as fh: # Fill_Line 1
_____________________ # Fill_Line 2
___________________ as fin: #Fill_Line 3
________________________ #Fill_Line 4
print(Rstu)
if Rstu["Marks"] >= 85:
print("Eligible for merit certificate")
else:
print("Not eligible for merit certificate")
(a) Complete Fill_Line1 so that the mentioned binary file is
opened for writing in fh object using a with statement.
(b) Complete Fill Line2 so that the dictionary Stul's
contents are written on the file opened in step (a).
(c) Complete Fill_Line3 so that the earlier created binary
file is opened for reading in a file object namely fin,
using a with statement.
(d) Complete Fill_Line4 so that the contents of open file in
fin are read into a dictionary namely Rstu
Ans:
(a) with open("stu.dat","wb") as fh: # Fill_Line1
(b) pickle.dump(stu1,fh) # Fill_Line2
(c) with open("stu.dat","rb") as fin: # Fill_Line3
(d) Rstu = pickle.load(fin) # Fill_Line4