DATA FILE HANDLING WORKSHEET - COMPLETE SOLUTIONS
TEXT FILE HANDLING
1. Give one difference between Text file and Binary File
Ans: Text files store data in human-readable format using character encoding (ASCII/UTF-8), while Binary
files store data in binary format (0s and 1s) which is not human-readable.
2. Write a Python statement to open a text file "[Link]" so that new contents can be
written on it.
Ans: file = open("[Link]", "w")
3. Write a Python statement to open a text file "[Link]" so that new content can be
added to the end of file
Ans: file = open("[Link]", "a")
4. Write a Python statement to open a text file "[Link]" so that existing contents can
be read from file.
Ans: file = open("[Link]", "r")
5. A file "[Link]" is opened as file1 = open("[Link]"). Write a Python
statement to close this file.
Ans: [Link]()
6. What is the different in file opening mode "a" and "w"?
Ans:
• "w" mode: Overwrites existing content, creates new file if doesn't exist
• "a" mode: Appends content to end of file, creates new file if doesn't exist
7. What is the significance of adding '+' with file opening mode, with context to 'r+'?
Ans: The '+' allows both reading and writing operations. 'r+' opens file for both reading and writing, file
pointer starts at beginning.
8. What is the difference between readline() and readlines()?
Ans:
• readline(): Reads only one line at a time
• readlines(): Reads all lines and returns them as a list
9. What is the purpose of using flush() in file handling operations?
Ans: flush() forces the internal buffer to write data immediately to the file instead of waiting for the buffer
to fill or file to close.
10. What is the advantage of opening file using 'with' keyword?
Ans: Automatically closes the file when the block ends, even if an error occurs. Ensures proper resource
management.
11. Considering the content stored in file "[Link]", Write the output of following
statements
python
f = open("[Link]")
str1 = [Link]() # to read first line of file
str2 = [Link]() # to read next line of file
str3 = [Link]() # to read remaining lines of file
Ans:
• str1 = "O Corona O Corona\n"
• str2 = "Jaldi se tum Go na\n"
• str3 = "Social Distancing ka palan karona\nsabse 1 meter ki duri rakhona\nLockdown me ghar me ho
to\nOnline padhai karona"
12. Complete the missing statement using 'for' loop to print all the lines of file
python
f = open("[Link]")
for line in f:
print(line)
13. What is the difference in write() and writelines()?
Ans:
• write(): Writes a single string to file
• writelines(): Writes a list of strings to file (doesn't add newlines automatically)
14. Considering the content stored in file "[Link]", write the output
python
f = open("[Link]")
print([Link](2))
print([Link](2))
print([Link](4))
Ans:
• In
• di
• a wo
15. Write a function in python to count the number of lines in "[Link]" begins from
Upper case character.
Ans: (Already provided in worksheet)
python
def UpperCase():
f = open('[Link]')
count = 0
for line in f:
if line[0].isupper():
count+=1
print("Lines starting from Capital letters: ",count)
[Link]()
16. Write a function in python to read lines from file "[Link]" and count how many
times the word "Corona" exists in file.
Ans: (Solutions already provided in worksheet)
17. Write a function in python to read lines from file "[Link]" and display all those
words, which has two characters in it.
Ans:
python
def TwoCharWords():
f = open('[Link]')
for line in f:
words = [Link]()
for word in words:
if len(word) == 2:
print(word, end=' ')
[Link]()
18. Write a function COUNT() in Python to read contents from file "[Link]", to
count and display the occurrence of the word "Catholic" or "mother".
Ans:
python
def COUNT():
f = open('[Link]')
content = [Link]().lower()
words = [Link]()
count = [Link]('catholic') + [Link]('mother')
print("Count of Catholic, mother is", count)
[Link]()
19. Write a function dispS() in Python to read from text file "[Link]" and display those
lines which starts with "S"
Ans:
python
def dispS():
f = open('[Link]')
for line in f:
if [Link]('S'):
print(line, end='')
[Link]()
20. Write a function COUNTSIZE() in Python to read the file "[Link]" and display size
of file.
Ans:
python
import os
def COUNTSIZE():
size = [Link]('[Link]')
print("Size of file is", size)
21. Write a python function ATOEDISP() for each requirement in Python to read the file
"[Link]"
Ans:
python
def ATOEDISP():
f = open('[Link]')
content = [Link]()
[Link]()
# (I) Replace A with E in COMPUTAR
content1 = [Link]('COMPUTAR', 'COMPUTER')
print(content1)
# (II) Replace all A with E
content2 = [Link]('A', 'E')
print(content2)
BINARY FILE HANDLING & CSV
1. _____ Letter is prefixed to store string in binary form
Ans: b (e.g., b'Hello')
2. Write a Python statement to open a text file "[Link]" in binary mode so that new
contents can be written on it.
Ans: file = open("[Link]", "wb")
3. Write a Python statement to open a text file "[Link]" in binary mode so that new
content can be added to the end of file
Ans: file = open("[Link]", "ab")
4. Write a Python statement to open a text file "[Link]" in binary mode so that existing
Ans: file = can
contents open("[Link]",
be read from "rb")file.
5. _____ function is used to convert string in binary form.
Ans: encode()
6. Consider the following Python code, and fill in the blank to complete the program
python
f=open("[Link]","wb")
str="India is my country"
[Link]([Link]()) # statement to store the str in file
[Link]()
7. _____ function is used to fetch binary data from binary file
Ans: read()
8. _____ function is used to convert binary string to string
Ans: decode()
9. _____ function is used in binary mode to send the read pointer to desired position
Ans: seek()
10. Consider a binary file which stores Name of employee, where each name occupies 20
bytes
Ans:
python
f = open("[Link]","rb")
s = [Link](20) # code to get first record
print([Link]())
[Link](80) # code to position at 5th record (4*20=80)
s = [Link](20)
print([Link]())
[Link](-20, 2) # code to position at last record
s = [Link](20)
print([Link]())
[Link]()
11. Write a Python statement to reposition the read pointer to 20 bytes back from the
Ans: [Link](-20,
current 1)
position.
12. Write a function RECCOUNT() to read the content of binary file '[Link]'
Ans: (Already provided in worksheet)
13. Write a function SCOUNT() to read the content of binary file '[Link]'
Ans:
python
def SCOUNT():
f = open('[Link]', 'rb')
count = 0
while True:
try:
name = [Link](20).decode().strip()
if name and name[0].upper() == 'S':
count += 1
except:
break
print("Total Names beginning from 'S' are", count)
[Link]()
14. To read and write collections like LIST, DICTIONARIES Python provides a module called
_____
Ans: pickle
15. _____ is the process of converting structures to byte stream before writing to file.
Ans: Pickling
16. _____ is the process of converting byte stream to original structure.
Ans: Unpickling
17. Pickling is done by the _____ function
Ans: dump()
18. Unpickling is done by the _____ function
Ans: load()
19. Consider the following Python code and complete the missing statement:
Ans: [Link](d, myfile)
20. Consider the following Python code and complete the missing statement:
Ans: d = [Link](myfile)
21. Python's standard streams are _____, _____, _____
Ans: stdin, stdout, stderr
22. Python's standard streams are available in _____ module
Ans: sys
23. From the given path identify the type of each:
Ans:
• (i) Absolute path
• (ii) Relative path
24. Consider the following Binary file '[Link]', Write a function RECSHOW()
Ans: (Already provided in worksheet)
25. CSV stands for _____
Ans: Comma Separated Values
26. _____ object is used to read data from csv file?
Ans: reader
27. _____ object is used to perform write operation on csv file.
Ans: writer
28. _____ function of writer object is used to send data to csv file to store.
Ans: writerow()
29. Write Python function DISPEMP() to read the content of file [Link] and display only
those records where salary is 4000 or above
Ans: (Already provided in worksheet)
30. Write a Python function DISPEMP() to count employees earning less than 5000
Ans:
python
import csv
def DISPEMP():
with open('[Link]') as csvfile:
myreader = [Link](csvfile, delimiter=',')
count = 0
for row in myreader:
if int(row[2]) < 5000:
count += 1
print("Employees earning less than 5000:", count)
31. Write Python function SNAMES() to read the content of file [Link]
Ans: (Already provided in worksheet)
32. Write a python function CSVCOPY() to take sourcefile, targetfile as parameter
Ans:
python
import csv
def CSVCOPY(sourcefile, targetfile):
with open(sourcefile) as source:
reader = [Link](source)
with open(targetfile, 'w', newline='') as target:
writer = [Link](target)
for row in reader:
[Link](row)