CH 5 Assignment
CH 5 Assignment
CLASS-XII
CHAPTER-5: FILE HANDLING
ASSIGNMENT – 1
UNSOLVED EXERCISES
4. Write statements to open a binary file C:\Myfiles\Text1.txt in read and write mode
by specifying the file path in two different formats.
Answer:
Format one:-
file = open ("C:\\Myfiles\\Text1.txt", 'r')
Format two:-
file = open (r"C:\Myfiles\Text1.txt", 'w')
Page 1 of 22
5. When a file is opened for output, what happens when
(i) The mentioned file does not exist
(ii) The mentioned file does exist
Answer :
(i) The mentioned file does not exist
• If file is open in read mode, then it gives error.
• If file is open in write or append mode then file created by python.
(ii) The mentioned file does exist
• If file is open in read mode, then python read the data according to program.
• If file is open in write mode, then python delete all data and write new
data according to user.
• If file is open in append mode, then the data in the file is retained and new
data being written will be appended to end.
6. What role is played by file modes in file operations? Describe the various file
mode constants and their meanings.
Answer :
File mode refers to how the file will be used once it's opened. There are
three types of file modes:-
(1) Read mode :- It will read data of file according to program.
(2) Write mode :- Python delete all data and write new data according to user.
(3) Append mode :- The data in the file is retained and new data being written will
be appended to end.
Page 2 of 22
(ii) Text form :
• It can easily understand by human.
• It can excess easily.
8. When do you think text files should be preferred over binary files?
Answer :
When people want to read the data of the file then text file easy to understand,
binary file not easily understand by human. At that time text files should be
preferred over binary files.
Page 3 of 22
TYPE: B – Application Based Questions [PAGE – 226, 227 & 228]
Page 4 of 22
>>> God made the Earth;
Man made confusing countries.
And their fancy-frozen boundaries.
But with unfound boundless Love
I behold the borderland of my India
Expanding into the world.
Hail, mother of religions, lotus, scenic beauty, and sages!
While, Output by (b) of Question 1 is that it will print 100 bytes data of
‘poemBTH.txt’
Output :
>>>God made the Earth;
Man made confusing countries.
And their fancy-frozen boundaries.
But with unfou <
3. Consider the file 'poemBTH.txt' given above (in previous question). What output
will be produced by following code fragment?
obj1 = open('poemBTH.txt', 'r')
s1 = obj1.readline()
s2.readline(10)
s3 = obj1.read(15)
print(s3)
print(obj1.readline())
obj1.close()
Answer :
Page 5 of 22
It will print error that ‘s2’ is not defined.
If you want any output then write code given below in python and make
poemBTH.txt in same directory :-
4. Consider the file 'poem.txt' and predict the output of following code fragments if
the file has been opened in file pointer file1 with code:
file1 = open (“E\\mydata\\poemBTH.txt”, ‘r+’)
(a)
print ("A. Output 1")
print (file1.read())
print ()
(b)
print ("B. Output 2")
print (file1.readline())
print ()
(c)
print ("C. Output 3")
print (file1.read(9))
print ()
(d)
Page 6 of 22
print ("D. Output 4")
print (file1.readline(9) )
(e)
print ("E. Output of Readlines function is")
print (file1.readlines() )
print ()
NOTE: Consider the code fragments in succession, i.e., code (b) follows code (a),
which means changes by code (a) remain intact. Similarly, code (e) follows (a) and (b),
and so on.
Answer :
After run all the programs output like that:
A. Output 1
God made the Earth;
Man made confusing countries.
And their fancy-frozen boundaries.
But with unfound boundless Love
I behold the borderland of my India
Expanding into the world.
Hail, mother of religions, lotus, scenic beauty, and sages!
B. Output 2
C. Output 3
D. Output 4
Page 7 of 22
5. What is following code doing?
file = open("contacts.csv", "a")
name = input("Please enter name.")
phno = input("Please enter phone number.")
file.write (name + "," + phone + "\n")
Answer:
It will take data from user and write data in file ‘contacts.csv’
6. Write code to open file created in previous question and print it in following
form:
Name : <name> Phone :< phone number>
Answer:
file = open("contacts.csv", "r")
data = file.readlines()
for i in data :
for j in range(len(i) +1 ) :
if i[ j ].isdigit() :
break
7. Consider the file "contacts.csv" created in above Q. and figure out what the
following code is trying to do?
Page 8 of 22
if name in line:
print (line)
Answer :
Name (Data) input from user and give the output if name (data) present in
"contacts.csv" file then give full details of that name(data), Otherwise it do nothing.
8. Consider the file poem.txt and predict the output of following code fragment.
What exactly is following code fragment doing?
nl = 0
for line in f:
nl += 1
print (nl)
Answer :
That program reads number of lines present in file "poem.txt".
9. If you use the code of Q.8 with pl.txt created in solved problem 14, what would
be its output?
Answer :
Its output is ‘one’, there is only one line present in file "pl.txt".
10. Write a method in python to read the content from a text file diary.txt line by
line and display the same on screen.
Answer :
Page 9 of 22
print (file.read())
11. Write a method in python to write multiple line of text content into a text file
mylife.txt line.
l = []
while True:
data = input("Enter the contents otherwise, Enter ""exit"" for
stop the program :")
if data == 'exit':
break
else :
l = l + [data + '\n']
file.writelines (l)
file.close ()
Page 10 of 22
TYPE: C – Programming Practices / Knowledge Based Questions
[PAGE – 228]
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.
Answer :-
lst = file1.readlines()
for i in lst :
word = i.split()
file2.write( " ".join(word) )
file2.write("\n")
file2.close()
file1.close()
OR
file1 = open("portal.txt","r")
file2 = open("Express.txt","w")
lst = file1.readlines()
for i in lst :
word = i.split()
for j in word :
file2.write( j + " ")
file2.write("\n")
file2.close()
file1.close()
Page 11 of 22
Like a joy on the heart of a sorrow,
The sunset hangs on a cloud;
A golden storm of glittering sheaves,
Of fair and frail and fluttering leaves,
The wild wind blows in a cloud.
Output :-
Answer :-
Page 12 of 22
import pickle
def portal( ) :
file1 = open("sports.dat","rb")
file2 = open("Atheletics.dat","wb")
try :
while True :
data = pickle.load( file1 )
word = data.split(" ~ ")
if data [ : 9 ] == "atheletic" or data [ : 9 ] ==
"Atheletic":
pickle.dump( data, file2 )
except EOFError :
file1.close()
file2.close()
print("Pragram Run Succesfully !!")
portal()
def portal( ) :
file1 = open("sports.txt","r")
file2 = open("Atheletics.txt","w")
lst = file1.readlines()
for i in lst :
print(i [ : 9 ])
if i [ : 9 ] == "atheletic" or i [ : 9 ] == "Atheletic" :
file2.write(i)
file1.close()
file2.close()
portal()
import pickle
f = open( "sports.dat","wb" )
pickle.dump("Football ~ Path",f)
pickle.dump("Atheletics ~ Walla",f)
pickle.dump("Cricket ~ Portal",f)
pickle.dump("Hockey ~ Express",f)
pickle.dump("Atheletics ~ Python",f)
pickle.dump("Chess ~ Computer",f)
f.close()
€
• ŒFootball ~ Path”.€
Page 13 of 22
• ŒAtheletics ~ Walla”.€
• ŒCricket ~ Portal”.€
• ŒHockey ~ Express”.€
• ŒAtheletics ~ Python”.€
• ŒChess ~ Computer”.
Output :-
€
• ŒAtheletics ~ Walla”.€
• ŒAtheletics ~ Python”.
Answer :-
for i in lst :
data = i.split()
print( data[0] ,end = "\t" )
print("|" , end = "\t")
print ( data[1] )
file.close()
Arvind 7258031
Sachin 7259197
Path 256445
Page 14 of 22
Walla 799645
Portal 6566363
Express 534553
Output :-
4. Write a program to count the words "to" and "the" present in a text file
"Poem.txt".
Answer :-
to_no = 0
the_no = 0
for i in lst :
word = i.split()
for j in word :
if j == "to" or j == "To" :
to_no += 1
elif j == "the" or j == "The" :
the_no += 1
file.close()
Poem.txt Contains :-
Page 15 of 22
Of fair and frail and fluttering leaves,
The wild wind blows in a cloud.
Output :-
Number 'to' : 3
Number 'the' : 7
>>>
5. Write a program to count the number of upper- case alphabets present in a text
file "Article.txt".
Answer :-
count = 0
file = open("Article.txt","r")
sen = file.read()
for i in range ( len(sen) ) :
if sen[ i ].isupper() :
count += 1
Article.txt Contains :-
Output :-
6. Write a program that copies one file to another. Have the program read the file
names from user ?
Page 16 of 22
Answer :-
data = old.read()
new.write( data )
old.close()
new.close()
Story.txt Contains :-
Output :-
7. Write a program that appends the contents of one file to another. Have the
program take the filenames from the user.
Answer :-
file1 = input("Enter the name of file which you want to append : ")
Page 17 of 22
file2 = input("Enter the name of original file : ")
data = old.read()
new.write( "\n" + data)
old.close()
new.close()
Story.txt Contains :-
Output :-
Enter the name of file which you want to append : Path Walla.txt
Enter the name of original file : story.txt
Program run successfully
>>>
Page 18 of 22
Answer :-
def DISPLAYWORDS() :
file = open("story.txt", "r")
lst = file.readlines()
for i in lst :
word = i.split()
for j in word :
if len( j ) < 4 :
print( j )
file.close()
Story.txt Contains :-
Output :-
A
boy
is
is
a
An
is
in
the
&
are
in
is
>>>
Page 19 of 22
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.
Answer :-
upper = open("UPPER.txt","w")
lower = open("LOWER.txt" , "w" )
other = open ("OTHER.txt" , "w")
while True :
user = input("Enter a charracter (for exit enter quit ): ")
if user == "quit" or user == "Quit" :
break
elif user.isupper() :
upper.write( user + " " )
elif user.islower( ) :
lower.write( user + " " )
else :
other.write( user + " " )
upper.close()
lower.close()
other.close()
print("Thankyou")
Output :-
Page 20 of 22
Enter a charracter (for exit enter quit ): t
Enter a charracter (for exit enter quit ): o
Enter a charracter (for exit enter quit ): n
Enter a charracter (for exit enter quit ): 3
Enter a charracter (for exit enter quit ): .
Enter a charracter (for exit enter quit ): 9
Enter a charracter (for exit enter quit ): .
Enter a charracter (for exit enter quit ): 5
Enter a charracter (for exit enter quit ): quit
Thankyou
>>>
UPPER.txt Contains :-
T P W P
LOWER.txt Contain :-
h i s i s a t h a l l t o n
OTHER.txt Contains :-
@ 3 . 9 . 5
10. Write a function in Python to count and display the number of lines starting
with alphabet 'A' present in a text file " LINES.TXT". e.g., the file
"LINES.TXT" contains the following lines:
Answer :-
count = 0
file = open("LINES.txt","r")
lst = file.readlines()
for i in lst :
if i[ 0 ] == "A" :
print(i)
count += 1
print()
print("So for number of sentences started with A : ",count)
Page 21 of 22
file.close()
Output :-
A boy is playing there.
An aeroplane is in the sky.
Alphabets & numbers are allowed in password.
Page 22 of 22