[go: up one dir, main page]

0% found this document useful (0 votes)
197 views9 pages

Data File Handling - Worksheet 1 - 5 Marks

This document is a worksheet for Grade 12 Computer Science focused on Data File Handling, specifically dealing with CSV and binary files. It includes various programming tasks and questions related to creating, reading, and manipulating CSV and binary files using Python functions. The worksheet covers topics such as file operations, user-defined functions, and the differences between binary and text files.

Uploaded by

Sushan Gopu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
197 views9 pages

Data File Handling - Worksheet 1 - 5 Marks

This document is a worksheet for Grade 12 Computer Science focused on Data File Handling, specifically dealing with CSV and binary files. It includes various programming tasks and questions related to creating, reading, and manipulating CSV and binary files using Python functions. The worksheet covers topics such as file operations, user-defined functions, and the differences between binary and text files.

Uploaded by

Sushan Gopu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Grade: 12 Computer Science

Data File Handling


Worksheet - 1
5 Marks

1.

2.

2. Write the full form of ‘CSV’. What is the default delimiter of csv files? The scores and ranks of
three students of a school level programming competition is given as: [‘Name’, ‘Marks’, ‘Rank’]
[‘Sheela’, 450, 1]
[‘Rohan’, 300, 2]
[‘Akash’, 260, 3]
Write a program to do the following:
(i) Create a csv file (results.csv) and write the above data into it.
(ii) To display all the records present in the CSV file named ‘results.csv’
OR
What does csv.writer object do?
3. Rohan is making a software on “Countries & their Capitals” in which various records are to
be stored/retrieved in CAPITAL.CSV data file. It consists some records(Country & Capital).
Help him to define and call the following user defined functions:
(i) AddNewRec(Country,Capital) – To accept and add the records to a CSV file
“CAPITAL.CSV”. Each record consists of a list with field elements as Country and
Capital to store country name and capital name respectively.
(ii) ShowRec() – To display all the records present in the CSV file named ‘CAPITAL.CSV’

Data File Handling Worksheet – 1 - 5 Marks Page 1


4.A binary file data.dat needs to be created with following data written it in the form of
Dictionaries.

Write the following functions in python accommodate the data and manipulate it.
a) A function insert() that creates the data.dat file in your system and writes the three
dictionaries.
b) A function() read() that reads the data from the binary file and displays the dictionaries whose
age is 16.
5.(a) What does CSV stand for?
(b) Write a Program in Python that defines and calls the following user defined functions:
(i) InsertRow() – To accept and insert data of an student to a CSV file ‘class.csv’. Each record
consists of a list with field elements as rollno, name and marks to store roll number, student’s
name and marks respectively.
(ii) COUNTD() – To count and return the number of students who scored marks greater than 75
in the CSV file named ‘class.csv’
6. Dhirendra 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'. He has succeeded in writing partial code and has missed out certain statements,
so he has left certain queries in comment lines.
importcsv
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

Data File Handling Worksheet – 1 - 5 Marks Page 2


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 Raman.
(i) Choose the appropriate mode in which the file is to be opened in append mode (Statement 1)
(ii) Which statement will be used to create a csv writer object in Statement 2.
(iii) Choose the correct option for Statement 3 to write the names of the column headings in the
CSV file, BOOKS.CSV.
(iv) Which statement will be used to read a csv file in Statement 4.
(v) Fill in the appropriate statement to check the field Title starting with ‘R’ for Statement 5 in the
above program
7.(a) What one advantage and one disadvantage of using a binary file for permanent storage?
(b) Write a Program in Python that defines and calls the following user defined functions: (i)
ADD() – To accept and add data of an item to a CSV file ‘events.csv’. Each record consists of
Event_id, Description, Venue, Guests, and Cost.
(ii) COUNTR() – To read the data from the file events.csv, calculate and display the average
number of guests and average cost.
8. (a) Give any one point of difference between a binary file and a text file.
(b) Write a Program in Python that defines and calls the following user definedfunctions: (i) ADD()
– To accept and add data of an item to a binary file ‘events.dat’. Each record of the file is a list
[Event_id, Description, Venue, Guests, Cost]. Event_Id, Description, and venue are of str type,
Guests and Cost are of int type.
(ii) COUNTR() – To read the data from the file events.dat, calculate and display the average
number of guests and average cost
9. Manoj 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 ______________ #Line1
def addCsvFile(UserName, Password):
fh=open('user.csv','_____________') #Line2
Newfilewriter=csv.writer(fh)
Newfilewriter.writerow([UserName,Password])
fh.close( )
# csv file reading code

Data File Handling Worksheet – 1 - 5 Marks Page 3


def readCsvFile(): #to read data from CSV file
with open('user.csv','r') as newFile:
newFileReader=csv.______(newFile) #Line3
for row in newFileReader:
print(row)
newFile.________________ #Line4
addCsvFile('Arjun','123@456')
addCsvFile('Arunima','aru@nima')
addCsvFile('Frieda','myname@FRD')
readCsvFile()
OUTPUT___________________ #Line 5
(a) What module should be imported in #Line1 for successful execution of the program? (b) In
which mode file should be opened to work with user.csv file in#Line2
(c) Fill in the blank in #Line3 to read data from csv file
(d) Fill in the blank in #Line4 to close the file (e) Write the output he will obtain while executing
Line5
10.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:

Data File Handling Worksheet – 1 - 5 Marks Page 4


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.
(a) Write the appropriate mode in which the file is to be opened in append mode (Statement 1)
(b) Which statement will be used to create a csv writer object in Statement 2.
(c) Write the correct option for Statement 3 to write the names of the column headings in the
CSV file, books.csv
(d) Write statement to be used to read a csv file in Statement 4.
(e) Fill in the appropriate statement to check the field Title starting with „R for Statement 5 in
the above program.
11. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
i. Write a user defined function CreateFile() to input data for a record and add to Book.dat .
ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter
and count and return number of books by the given Author are stored in the binary file
“Book.dat”
12. 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%
13. Vijay of class 12 is writing a program to create a CSV file “mydata.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): # write data into the CSV file
f=open(' mydata.csv','________') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()
def readCsvFile(): # read data from CSV file
with open('mydata.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:

Data File Handling Worksheet – 1 - 5 Marks Page 5


print (row[0],row[1])
newFile.______________ # Line 4

addCsvFile(“Aman”,”123@456”)
addCsvFile(“Vijay”,”aru@nima”)
addCsvFile(“Raju”,”myname@FRD”)
readCsvFile()
(i) Give Name of the module he should import in Line 1.
(ii) In which mode, Vijay should open the file to add data into the file in Line2.
(iii) Complete the Line 3 to read the data from csv file and Line 4 to close the file
14. What is the significance of a delimiter symbol in a csv file? Write a Program in Python that
defines and calls the following user defined functions:
(i) ADD_CONT() – To accept and add data of a contact to a CSV file ‘address.csv’. Each record
consists of a list with field elements as contId, cname and cmobile to store contact id, contact
name and contact number respectively.
(ii) COUNT_CONT() – To count the number of records present in the CSV file named ‘address.csv’
15. How csv file is different from a binary file? Write a Program in Python that defines and calls
the following user defined functions:
(i) save() – To accept and add data of watches to a CSV file ‘watchdata.csv’. Each record consists
of a list with field elements as watchid, wname and wprice to store watch id, watch name and
watch price respectively.
(ii) search()- To display the records of the watch whose price is more than 6000.
16. Vaishanavi is a budding Python programmer. She has written a code and created a binary
file phonebook.dat with contactNo, name and blocked [ Y/ N ]. The file contains 10 records as a
dictionary like {‘contactNo’ : 32344455 , ‘name’: ‘kamalkant’ ,’blocked’ : “Y” }
She now wants to shift all the records which have blocked = ‘Y’ status from phonebook.dat to a
binary file blocked.dat also all records which have blocked = ‘N’ status from phonebook.dat to
unblocked.dat. She also wants to keep count and print the total number of blocked and
unblocked records. As a Python expert, help her to complete the following code based on the
requirement given above:
import _____________ #Statement 1
def shift_contact( ):
fin = open(“phonebook.dat”,’rb’)
fblock = open( ___________________ ) #Statement 2
funblock = open( ___________________ ) #Statement 3
while True :
try: rec = __________________ # Statement 4

Data File Handling Worksheet – 1 - 5 Marks Page 6


if rec[“blocked”] == ‘Y’:
pickle.__________________ #Statement 5
if rec[“blocked”] == ‘N’:
Pickle. ________________ # Statement 6
except:
break
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a blocked.dat and unblocked.dat binary files
(Statement 2 and 3)
(iii) which statement should Vaishnavi use in statement 4 to read the data from the binary file,
phonebook.dat
(iv) which statement should Vaishnavi use in statement 5 and 6 to write data to the blocked.dat
and unblocked.dat
17.Sumit is a programmer who is working on a project that requires student data of a school to
be stored in a CSV file. Student data consists of roll no, name, class and section. He has written
a program to obtain the student data from user and write it to a CSV file. After getting errors in
the program he left five statements blank in the program as shown below. Help him to find the
answer 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.

Data File Handling Worksheet – 1 - 5 Marks Page 7


(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?
18. What are the advantages of binary file over text file? Write a Python program in Python to
search the details of the employees (name, designation and salary) whose salary is greater than
5000. The records are stored in the file emp.dat. consider each record in the file emp.dat as a list
containing name, designation and salary.
19. (a) What is the advantage of using a csv file for permanent storage?
(b) Write a Program in Python that defines and calls the following user defined functions: (i)
ADD() – To accept and add data of an item to a CSV file ‘furniture.csv’. Each record consists of
Fur_id, Description, Price, and Discount.
(ii) COUNTR() – To count the number of records present in ‘furniture.csv’ whose price is less than
5000.
20. (a) Give any one point of difference between a binary file and a csv file.
(b) Write a Program in Python that defines and calls the following user defined functions: (i)
ADD() – To accept and add data of an item to a binary file ‘furniture.dat’. Each record of the file
is a list [Fur_id, Description, Price, and Discount]. Fur_Id and Description are of str type, Price is
of int type, and Discount is of float type.
(ii) COUNTR() – To count the number of records present in ‘furniture.dat’ whose price is less than
5000.
21. Given a binary file “emp.dat” has structure (Emp_id, Emp_name, Emp_Salary). Write a
function in Python countsal() in Python that would read contents of the file “emp.dat” and
display the details of those employee whose salary is greater than 20000.
22. A binary file “Stu.dat” has structure (rollno, name, marks).
(i) Write a function in Python add_record() to input data for a record and add to Stu.dat. (ii) Write
a function in python Search_record() to search a record from binary file “Stu.dat” on the basis of
roll number
23. Write a function SCOUNT( ) to read the content of binary file “NAMES.DAT and display
number of records (each name occupies 20 bytes in file ) where name begins from “S in it.
For.e.g. if the content of file is:
SACHIN
AMIT
AMAN
SUSHIL
DEEPAK

Data File Handling Worksheet – 1 - 5 Marks Page 8


HARI
SHANKER
Function should display
Total Names beginning from “S” are 2
24. Consider the following CSV file (emp.csv):
Sl,name,salary
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
Write Python function DISPEMP( ) to read the content of file emp.csv and display only those
records where salary is 4000 or above
25. Consider an employee data, Empcode, empname and salary. Write python function to create
binary file emp.dat and store their records. 2. write function to read and display all the records

Data File Handling Worksheet – 1 - 5 Marks Page 9

You might also like