0% found this document useful (0 votes)
160 views

Data File Handling Worksheet

Uploaded by

Chithra Pillai
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)
160 views

Data File Handling Worksheet

Uploaded by

Chithra Pillai
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/ 10

SHRI RAM GLOBAL, WHITEFIELD, BLR-67

SUBJECT: COMPUTER SCIENCE


CH: 4-DATA FILE HANDLING WORKSHEET

Long Answer Questions:- (Case study based questions)


1) Shantanu of class 12 is writing a program to create a CSV file “BoardDetails.csv” which
will contain BoardRollNo, StuName, DateOfBirth 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(BoardRollNo,StuName,
DateOfBirth):
f =open ('________________,'a',newline='') #Line 2
x = csv.writer (f)
x.writerow ([BoardRollNo,StuName, DateOfBirth])
f.close () def readCsvFile(): f=open
('BoardDetails.csv','__') #Line 3 y=
csv._________ #Line 4
for row in y: if
(int(row[0])>9107750):
print (row[0],row[1]) f.close()
addCsvFile (9107752,"Sita Sharma","2003/10/21") addCsvFile
(9107751,"Gita Patel","2004/11/01")
addCsvFile (9107750,"Suresh Rao","2003/10/25")
readCsvFile () #Line 5
(a) Name the module he should import in Line
(b) Fill in the blank in Line 2 to open the file to write/add data into the file.
(c) Fill in the blank in line 3 to read from the csv file. (d) Fill in the blank in Line 3 to read
data from the csv file (e) Write the output he will obtain while executing Line 5.

2. MOHIT of class 12 is writing a program to search a name in a CSV file “MYFILE.csv”.


He has written the following code. As a programmer, help him to successfully execute the
given task.
import _________ # Statement 1
f = open("MYFILE.csv", _______) # Statement 2
data = ____________ ( f ) # Statement 3
nm = input("Enter name to be searched: ")
for rec in data: if rec[0] == nm:
print (rec)
f.________ ( ) # Statement 4
(a) Name the module he should import in Statement 1.
(b) In which mode, MOHIT should open the file to search the data in the file in Statement 2?
(c) Fill in the blank in Statement 3 to read the data from the file.
(c) Fill in the blank in Statement 4 to close the file.
(d) Write the full form of CSV

3. Your teacher has given you a method/function FilterWords() in python which read lines
from a text file NewsLetter. TXT, and display those words, which are lesser than 4
characters. Your teachers intentionally kept few blanks in between the code and asked you to
fill the blanks so that the code will run to find desired result. Do the needful with the
following python code. def FilterWords(): 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
__________ #Statement-6
a) Write the correct mode of opening the file in statement-1?
b) Fill in the blank in statement-2 to read the data from the file.
c) Fill in the blank in statement-3 to read data word by word.
d) Fill in the blank in statement-4, which display the word having lesser than 4 characters.
e) Fill in the blank in Statement-5 to close the file.
f) Fill in the blank in Statement-6 to call the function FilterWords().

4. Arun, during Practical Examination of Computer Science, has been assigned an incomplete
search () function to search a record which is passed as parameter in a pickled file student.dat.
The File student.dat is created by his Teacher and the following information is known about
the file.
(a) File contains details of students in [roll_no,name,marks] format.
(b) 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 number1. def search(r):
f = open(“student.dat”,____) #Statement-1
____: #Statement-2
while True:
rec = pickle.____ #Statement-3
if(____): #Statement-4
________ #Statement-5 except:
pass
_____________ #Statement – 6
a) In which mode Arun should open the file in Statement-1?
b) Write the suitable code to be used at blank space in line marked as Statement-2.
c) Write the function (with argument), to be used at blank space in line marked as Statement-
3.
d) What will be the suitable code for blank space in line marked as Statement-4?
e) What will be the suitable code for blank space in line marked as Statement-5 to show record?
f) Which statement Arun should use at blank space in line marked as Statement-6 to close the
file?

TEXT FILE BASED FUNCTION QUESTIONS:


1. Write a function AMCount() in Python, which should read each character of a text file
STORY.TXT, should count and display the occurrence 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

2. 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

3. Write a function Show_words() in python to read the content of a text file


‘NOTES.TXT’ and display only such lines of the file which have exactly 5 words in
them.
Example, if the file contains: “This is a sample file. The file contains many sentences.
But need only sentences which have only 5 words.” Then the function should display
the output as: This is a sample file.
4. Write a method COUNTLINES () in Python to read lines from text file
‘TESTFILE.TXT’ and display the lines which are not starting with any vowel.
Example:”If the file content is as follows: An apple a day keeps the doctor away. We
all pray for everyone’s safety. A marked difference will come in our country.” The
COUNTLINES () function should display the output as:
The number of lines not starting with any vowel – 1

5. 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
6. Write a function RevString() prints the words to read a text file “Input.txt” and print
the words starting with ‘O’ in reverse order. The rest of the content is displayed
normally.
Example: If content in the text file is: UBUNTU IS AN OPEN SOURCE OPERATING
SYSTEM Output will be: UBUNTU IS AN NEPO SOURCE GNITAREPO SYSTEM

BINARY FILE BASED FUNCTION QUESTIONS

1. A binary file “Stock.dat” has structure [ItemNo, Item_Name, Company_Name,


Cost_Price,Selling_Price].
i. Write a user defined function CreateStockFile() to input data for a record
and add ItemNo, Item_Name, Company, Cost_Price and Selling_Price to
“Stock.dat” .
ii. Write a function CountRow(Company_Name) in Python which accepts
the Company_Name as parameter and count and return number of Items
by the given Company that are stored in the binary file “Stock.dat.

2. 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%.
3. A binary file “emp.DAT” has structure (EID, Ename, designation,salary).
i. Write a function to add more records of employes in existing file emp.dat.
ii. Write a function Show () in Python that would read detail of employee
from file “emp.dat” and display the details of those employee whose
designation is “Salesman”.
4. Given a csv file GAME.CSV, containing records of the following structure type:
[GameName , Participant]. Write a function in python that would read contents from
the file GAME.CSV and creates a file named BASKET. CSV copying only those
records from GAME.CSV where the game name is “Basket Ball.

5. 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
6. 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 records as dictionaries.
b) A function read() that reads the data from the binary file and displays the records
as dictionaries whose age is 16.

CSV FILE BASED FUNCTION QUESTIONS:-

1. Write a Program in Python that defines and calls the following user defined functions:
(i) add () – To accept and add data of an employee to a CSV file ‘employee.csv’.
Each record consists of a list with field elements as eid, name and salary to store
employee id, employee name and employee salary respectively.
(ii) search ()- To display the records of the employee whose salary is more than
40000.
2. 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'. 3. Write a Program in Python that defines and calls the
following user defined functions:

3. 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.
4. 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.
5. 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: Help him to define those two functions as per the following
instructions.
(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'.
6. 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.
(iii) COUNT_CONT() – To count the number of records present in the CSV file named
‘address.csv’

OUTPUT QUESTIONS

1. A text file “abc.txt” containing the following data:


“A switch is called an intelligent hub as it forwards the data packets only to the intended
nodes.”
Considering the above text file and Give the output of the following code:-
f=open (“C:\\abc.txt”,”r”) f.seek(10) k=f.read() # starts reading
from the 10th character print(k)
f.seek(5) k=f.read() # starts reading from
the 5th character print (k)

2. Give the output of the following code in context of file “abc.txt”:-


f=open(“C:\\abc.txt”,”r”) f.seek(10) t=f.tell() print(“current
position=”,t)
k=f.read() # starts reading from the 10th character print(k)
f.seek(5) t=f.tell()
print(“current
position=”,t)
k=f.read() # starts reading from the 5th character print(k)

Absolute Path
An absolute path is a path that contains the entire path to the file or directory that you need to
access. Absolute paths ensure that Python can find the exact file on your computer. Absolute
file paths start with a leading forward slash and describe how to access a given file or directory,
starting from the root of the file system.
Relative Path
Generally ’.’ represents the absolute path of the folder where the py file is currently located
(parent folder), and ’..’ represents the absolute path of the upper level folder(parent of parent),
of the parent folder where the py file is currently located If you don’t add a dot, it means the
same layer as the py file, that is, the default. The term “parent” directory/folder is used to
describe the preceding folder in which a subfolder or file is created. A parent folder can have
many subfolders or files; thus, many subfolders can share the same parent folder.

Let’s take an example, a folder Test is created in C:\, Two subfolders Test1, Test2 and one
“x.txt” is created in Test Folder. “y.txt” and “Try.py” are created in folder Test1 and “z.txt” is
created in Test2

Differentiate between Binary Files and Text Files.


• Text files: In this type of file, each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘\n’) in python by default. A text
file stores data in the form of alphabets, digits and other special symbols by storing their ASCII
values and are in a human readable format.
• Binary files: In this type of file, there is no terminator for a line and the data is stored
after converting it into machine understandable binary language. A binary file stores the data
in the same way as stored in the memory. The .exe files, mp3 file, image files, word documents
are some of the examples of binary files. We can’t read a binary file using a text editor

You might also like