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

CH 5 Assignment

Uploaded by

saumyaagarwal682
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

CH 5 Assignment

Uploaded by

saumyaagarwal682
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

SUBJECT – COMPUTER SCIENCE

CLASS-XII
CHAPTER-5: FILE HANDLING

ASSIGNMENT – 1

UNSOLVED EXERCISES

TYPE: A – Short Answer Questions / Conceptual Questions [PAGE – 226]

1. What is the difference between "w" and "a" mode?


Answer :
"w" mode :- If file exists, python will delete all data of the file.
"a" mode :- If file exists, the data in the file is retained and new data being written
will be appended to end.

2. What is the significance of file-object?


Answer :
All functions that we perform on a data file are performed through file-objects.

3. How is file open() function different from close() function ?


Answer:
open () function is a built-in function while close () function is a method used with file
handle object.

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.

7. What are the advantages of saving data in:


(i) Binary form (ii) Text form
Answer : (i) Binary form :
• It is faster and use less memory.
• Computer can easily understand this form.
• We Can Store Any type of Data in it.

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.

9. Write a statement in Python to perform the following operations:


(a) To open a text file "BOOK.TXT" in read mode.
(b) To open a text file "BOOK.TXT" in write mode.
Answer :
(a) File = open ("BOOK.txt", 'r')
(b) File = open ("BOOK.txt", 'w')

Page 3 of 22
TYPE: B – Application Based Questions [PAGE – 226, 227 & 228]

1. How are following codes different from one another?


(a)
my_file = open('poem.txt', 'r')
my_file .read()
(b)
my_File = open('poem.txt", "r)
my_file .read(100)
Answer :
(a) will read all data of 'poem.txt'
(b) read only 100 bytes

2. If the tile 'poemBTH.txt' contains the following poem (by Paramhansa


Yogananda):
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!
• Then what outputs will be posted by both the code fragments given in question 1.
Answer :
Output by (a) of Question 1 is that it will print all data of 'poemBTH.txt' in another
word, it will print full poem.
Output :

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 :-

obj1 = open('Pathwalla.txt', 'r')


s1 = obj1.readline()
s2 = obj1.readline(10)
s3 = obj1.read(15)
print(s3)
print(obj1.readline())
obj1.close()

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

E. Output of Readlines function is


[]
* This is because python read data only one time in a particular program.

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() :

print("Name :",i[ : j-1]," Phone :",i[ j : ])

break

7. Consider the file "contacts.csv" created in above Q. and figure out what the
following code is trying to do?

name = input("Enter name :")

file = open("contacts.csv", "r")

for line in file:

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?

f = open ("poemBTH.txt", "r")

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 :

file = open("diary.txt", "r")

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.

Answer :("mylife.txt", "w")

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 :-

file1 = open("Path Walla.txt","r")


file2 = open("Portal Express.txt","w")

lst = file1.readlines()

for i in lst :
word = i.split()
file2.write( " ".join(word) )
file2.write("\n")

print("Program has successfully run")

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")

print("Program has successfully run")

file2.close()
file1.close()

Path Walla.txt Contains :-

This is the Path Walla Website.


We are going to do some Python code

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.

Hark to a voice that is calling


To my heart in the voice of the wind:
My heart is weary and sad and alone,
For its dreams like the fluttering leaves have
gone,
And why should I stay behind?

Output :-

Program has successfully run


>>>

Portal Express.txt Contains :-

This is the Path Walla Website.


We are going to do some Python code

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.

Hark to a voice that is calling


To my heart in the voice of the wind:
My heart is weary and sad and alone,
For its dreams like the fluttering leaves have gone,
And why should I stay behind?

2. A file sports.dat contains information in following format :


Event ~ Participant
Write a function that would read contents from file sports.dat and creates a file
named Atheletic.dat copying only those records from sports.dat where the event
name is "Athletics".

Answer :-

Binary File Program :-

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()

Text File Program :-

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()

We write Data in sports.dat file by following script

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()

sports.dat file contain :- ( in Binary Language)


• ŒFootball ~ Path”.€

Page 13 of 22
• ŒAtheletics ~ Walla”.€
• ŒCricket ~ Portal”.€
• ŒHockey ~ Express”.€
• ŒAtheletics ~ Python”.€
• ŒChess ~ Computer”.

Output :-

Program Run Successfully !!


>>>

Atheletic.dat file Contain :- ( in Binary Language )


• ŒAtheletics ~ Walla”.€
• ŒAtheletics ~ Python”.

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.

Answer :-

print("Name\t|\tPhone no. ")

file = open("Path Walla.txt", "r")


lst = file.readlines()

for i in lst :
data = i.split()
print( data[0] ,end = "\t" )
print("|" , end = "\t")
print ( data[1] )

file.close()

Path Walla.txt Contains :-

Arvind 7258031
Sachin 7259197
Path 256445

Page 14 of 22
Walla 799645
Portal 6566363
Express 534553

Output :-

Name | Phone no.


Arvind | 7258031
Sachin | 7259197
Path | 256445
Walla | 799645
Portal | 6566363
Express | 534553
>>>

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

file = open("Poem.txt", "r")


lst = file.readlines()

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

print("Number 'to' : " , to_no)


print("Number 'the' : " , the_no)

file.close()

Poem.txt Contains :-

This is the Path Walla Website.


We are going to do some Python code

Like a joy on the heart of a sorrow,


The sunset hangs on a cloud;
A golden storm of glittering sheaves,

Page 15 of 22
Of fair and frail and fluttering leaves,
The wild wind blows in a cloud.

Hark to a voice that is calling


To my heart in the voice of the wind:
My heart is weary and sad and alone,
For its dreams like the fluttering leaves have gone,
And why should I stay behind?

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

print("Number of upper case alphabet : ", count)


file.close()

Article.txt Contains :-

A boy is playing there.


There is a playground.
An aeroplane is in the sky.
Alphabets & numbers are allowed in password.
This is Path Walla Website..

Output :-

Number of upper case alphabet : 8


>>>

6. Write a program that copies one file to another. Have the program read the file
names from user ?

Page 16 of 22
Answer :-

file1 = input("Enter the name of original file :- ")


file2 = input("Enter the name of New file :- : ")

old = open( file1 , "r")


new = open( file2, "w")

data = old.read()
new.write( data )

print(" Program run successfully ")

old.close()
new.close()

Story.txt Contains :-

A boy is playing there.


There is a playground.
An aeroplane is in the sky.
Alphabets & numbers are allowed in password.
This is Path Walla Website.

Output :-

Enter the name of original file :- story.txt


Enter the name of New file :- : Path Walla.txt
Program run successfully
>>>

Path Walla.txt Contains :-

A boy is playing there.


There is a playground.
An aeroplane is in the sky.
Alphabets & numbers are allowed in password.
This is Path Walla Website.

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 : ")

old = open( file2 , "r" )


new = open( file1 , "a" )

data = old.read()
new.write( "\n" + data)

print("Program run successfully ")

old.close()
new.close()

Story.txt Contains :-

A boy is playing there.


There is a playground.
An aeroplane is in the sky.
Alphabets & numbers are allowed in password.
This is Path Walla Website.

Initially Path Walla.txt Contains :-

Python is Best Pragamming Language in The whole World

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

Finally Path Walla.txt Contains :-

Python is Best Pragamming Language in The whole World

A boy is playing there.


There is a playground.
An aeroplane is in the sky.
Alphabets & numbers are allowed in password.
This is Path Walla Website.

8. Write a method/function DISPLAYWORDS() in python to read lines from a text


file STORY.TXT, and display those words, which are less than 4 characters.

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()

print("Word with length smaller than 3 :- \n")


DISPLAYWORDS()

Story.txt Contains :-

A boy is playing there.


There is a playground.
An aeroplane is in the sky.
Alphabets & numbers are allowed in password.
This is Path Walla Website.

Output :-

Word with length smaller than 3 :-

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 :-

Enter a charracter (for exit enter quit ): T


Enter a charracter (for exit enter quit ): h
Enter a charracter (for exit enter quit ): i
Enter a charracter (for exit enter quit ): s
Enter a charracter (for exit enter quit ):
Enter a charracter (for exit enter quit ): i
Enter a charracter (for exit enter quit ): s
Enter a charracter (for exit enter quit ):
Enter a charracter (for exit enter quit ): P
Enter a charracter (for exit enter quit ): a
Enter a charracter (for exit enter quit ): t
Enter a charracter (for exit enter quit ): h
Enter a charracter (for exit enter quit ):
Enter a charracter (for exit enter quit ): W
Enter a charracter (for exit enter quit ): a
Enter a charracter (for exit enter quit ): l
Enter a charracter (for exit enter quit ): l
Enter a charracter (for exit enter quit ):
Enter a charracter (for exit enter quit ): @
Enter a charracter (for exit enter quit ): P

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:

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.

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.

So for number of sentences started with A : 3


>>>
--------------------------x--------------------------

Page 22 of 22

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy