Class XII
Computer Science
Chapter : Data File Handling
(Programming Practice / Knowledge Based Questions)
Q.1 Write a program that reads a text file and creates another file that is identical except
that every sequence of consecutive blank spaces is replaced by a single space.
file1 = open("[Link]","r")
file2 = open("[Link]","w")
lst = [Link]()
for i in lst :
word = [Link]()
[Link]( " ".join(word) )
[Link]("\n")
print("Program has successfully executed")
[Link]()
[Link]()
Q.2 A file [Link] contains information in following format :
Event ~ Participant
Write a function that would read contents from file [Link] and creates a file
named
[Link] copying only those records from [Link] where the event name is
"Atheletics ".
def athlete(f1,f2):
l=[Link]() #reading the first file as a list
for line in l:
if 'Athletics' in line: #only those line where 'Athletics' is mentioned.
[Link](line)
[Link]('\n')
#main function
[Link]("[Link]","r")
[Link]("[Link]","w")
athlete(f1,f2) #calling function in main
Q.3 A file contains a list of telephone numbers in the following form:
Arvind 7258031
Sachin 7259197 .
The names contain only one word the names and telephone numbers are separated
by
white spaces.
Write program to read a file and display its contents in two columns.
1
print("Name Phone No")
file = open("[Link]", "r")
lst = [Link]()
for i in lst :
data = [Link]()
print(data[0],"\t", data[1])
[Link]()
Q.4 Write a program to count the words "to" and "the" present in a text file
"[Link]".
to_no = 0
the_no = 0
file = open( "[Link]", "r" )
lst = [Link]()
for i in lst :
word = [Link]()
for j in word :
if j == "to" or j== "To" :
to_no+= 1
elif j == "the" or j == "The" :
the_no+=1
print ( "Number 'to' : " , to_no)
print ( "Number 'the' : " , the_no)
[Link]()
Q.5 Write a program to count the number of upper- case alphabets present in a text file
"[Link]"
count = 0
file = open("[Link]","r")
r = [Link]()
for i in range(len(r)):
if r[i].isupper():
count += 1
print("Number of upper case alphabet : ", count)
[Link]()
Q.6 Write a program that copies one file to another. Have the program read the file
names
from user ?
f1_name=input("Enter first file's name along with extension name:")
# File to be read from
f2_name=input("Enter second file's name along with extension name:")
# File to be written to
2
f1=open(f1_name,"r")
f2=open(f2_name,"w")
l=[Link]() # creates a list of all the lines from the first file
for line in l:
[Link](line) # every line contains the n character
[Link]()
[Link]()
Q.7 Write a program that appends the contents of one file to another. Have the program
take the filenames from the user.
f1_name=input("Enter first file's name:") # File to be read from
f2_name=input("Enter second file's name:") # File to be written to
f1=open(f1_name,"r")
f2=open(f2_name,"a") # it don’t truncate the contents of the 2nd file
l=[Link]() # creates a list of all the lines in the first file
for line in l:
[Link](line) # every line contains the n character
[Link]()
[Link]()
Q.8 Write a method/function DISPLAYWORDS() in python to read lines from a text file
[Link], and display those words, which are less than 4 characters.
def DISPLAYWORDS():
file = open("[Link]", "r")
lst = [Link]()
for i in lst:
word = [Link]()
for j in word:
if len( j ) < 4:
print( j )
[Link]()
#main function
DISPLAYWORDS()
Q.9 Write a program that reads characters from the keyboard one by one. All lower case
characters get stored inside the file LOWER, all upper case characters get stored
inside the file UPPER and all other characters get stored inside file OTHERS.
upper = open ( "[Link]","w" )
lower = open ( "[Link]" , "w" )
other = open ( "[Link]" , "w" )
while True :
user = input("Enter a character (for exit enter quit ): ")
if user == "quit" or user == "Quit" :
break
elif [Link]() :
3
[Link]( user + " " )
elif [Link]( ) :
[Link]( user + " " )
else :
[Link]( user + " " )
[Link]()
[Link]()
[Link]()
Q.10 Write a function in Python to count and display the number of lines starting with
alphabet 'A' present in a text file " [Link]". e.g., the file "[Link]"
contains the following lines:
A boy is playing there.
There is a playground.
An aeroplane is in the sky.
Alphabets & numbers are allowed in password.
The function should display the output as 3.
def func(l):
count = 0
for i in l:
if i[0]=="A":
count += 1
return count
file=open("[Link]","r")
l= [Link]()
print ( "No of Lines started with A : ", func(l) )
[Link]()
Q.11 Write a function in Python to count and display the number of lines starting with
alphabet A present in a text file [Link].
count = 0
file = open("[Link]","r")
lst = [Link]()
for i in lst :
if i[ 0 ] == "A" :
print(i)
count += 1
print()
print("So for number of sentences started with A : ",count)
[Link]()
4
Q.12 Write a program that counts the number of characters up to the first $ in a text file.
file = open("[Link]","r")
data = [Link]()
cnt=0
for i in range( len( data ) ):
for j in range( len( data[ i ] ) ):
if data [ i ][ j ] == "$" :
break
else:
cnt+=1
print( "Total number of characters up to the first $ befor = ",cnt )
[Link]()
Q.14 Consider the following definition of dictionary Member, write a method in python
to
write the content in a pickled file [Link].
import pickle
file = open("[Link]","wb")
while True :
dic={}
no = int(input("Enter memberbno. :-"))
name = input("Enter name:-")
dic[ "Memberno."] = no
dic["Name"] = name
[Link]( dic, file )
user = input("For quit enter quit :-")
if user == "quit":
break
print("Thankyou")
[Link]()
Q.15 Consider the following definition of dictionary Staff, write a method in python to
search and display the content in a pickled file [Link], where Staffcode key of the
dictionary is matching with 'S0105'.
import pickle
file = open("[Link]", "rb")
found = 0
try :
while True :
staff = [Link](file)
if staff [ "Staff Code" ] == 'S0105':
5
print(staff)
found=1
except EOFError :
if found == 0:
print("Not found !!!")
[Link]()
Q.16 Considering the following definition of dictionary COMPANY, Write a method in
Python to search and display the content in a pickled file [Link], where
CompID key of the dictionary is matching with the value '1005'.
Company = {'CompID' = ____, 'CName' = ____, ‘Turnover’ = ____}
import pickle
file = open("[Link]","rb")
found = 0
try :
while True :
Company = [Link](file)
if Company [ "CompID" ] == '1005':
print(Company)
found=1
except EOFError :
if found == 0:
print("Not found !!!")
[Link]()
Q.17 Write a function in to search and display details of all trains, whose destination is
Delhi from a binary file [Link]. Assuming the binary file is containing the
objects of the following dictionary type:
Train = { 'Tno': ___, ‘From’: ____, 'To' : ____}
import pickle
def search() :
file = open("[Link]","rb")
found = 0
try :
while True :
Train = [Link](file)
if Train [ "To" ] == 'Delhi':
print(Train)
found=1
6
except EOFError :
if found == 0:
print("Not found !!!")
[Link]()
search()
Q.18 A binary file "[Link]" has structure [BookNo, Book Name, Author, Price].
(i) Write a user defined function CreateFile() to input data for a record and add to
[Link].
(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 "[Link]".
import pickle
def CreateFile():
f = open("[Link]", "wb")
while True :
num = int(input("Enter Book Number :- "))
name = input ("Enter Book Name :- ")
aut = input("Enter Author :- ")
pri = float(input("Enter Price of Book :- "))
lst= [ num, name, aut, pri]
[Link]( lst, f)
choice = input("For exit (Enter exit):- ")
print()
if choice == "exit" or choice == "Exit":
print("Thank you")
print()
break
[Link]()
def CoutRec():
print("For Searching -")
aut = input("Enter Author :- ")
f = open("[Link]", "rb")
count = 0
try :
while True:
data = [Link](f)
if data[2] == aut :
count += 1
except EOFError:
[Link]()
7
print("Number of Book with Author name", aut , "=", count)
CreateFile()
CoutRec()
Q.20 Write a Python program to read a given CSV file having tab delimiter.
import csv
file = open( "[Link]","r" )
data = [Link](file, delimiter = "|")
for i in data :
print(i)
[Link]()
Q. 21 Write a Python program to write a nested Python list to a csv file in one go. After
writing the CSV read the CSV file and display the content.
import csv
file = open( "[Link]","r+" )
lst = eval(input("Enter a nested list :-"))
ais_write = [Link]( file)
ais_write.writerows( lst )
data = [Link](file)
for i in data :
print(i)
Q.23 Write a function that reads a csv file and creates another csv file with the same
content except the lines beginning with 'check'.
import csv
def MyFunc( file1 ):
file2 = open( "[Link]","w",newline="" )
portal_write = [Link]( file2 , delimiter = "|")
data = [Link](file1)
for i in data :
if i[0][:5] != "check" :
portal_write.writerow( i )
[Link]()
file1 = open( "[Link]","r" )
8
MyFunc( file1 )
print ("Thank You !!")
Q.24 Write a function show_Words() in python to read the content of a text file
“[Link]”
and display only such lines of the file which have exactly 5 words in them
import pickle
f = open("[Link]", "rb")
while True:
line = [Link](f)
word = [Link]()
if len( word ) == 5 :
print( line )
[Link]()
import pickle
f = open("[Link]", "wb")
[Link]("This is a sample file.",f)
[Link]("The file contains many sentences.", f)
[Link]("But We need only sentences which have only 5 words.", f)
[Link]("", f)
[Link]("My Website is Ajmani International.", f)
[Link]("This is a school.", f)
[Link]("I love Python.", f)
[Link]("", f)
[Link]()