Meenakshi Group Of Institutions
Vani Vidyalaya Senior Secondary & Junior College
Class XII Computer Science
Chapter 5 File Handling Study Material
Text Files
a)writegroup() b)write()
c)writechar() d)writeall()
12. Which function is used to write List of strings on to the text file? C
a)writelist() b)writeline()
c)writelines() d)writeall()
13. In which mode text file should be opened to add the data at the end to the C
text file?
a)‟r‟ b)‟w‟
c)‟a‟ d)‟b‟
14. Which of the following command can be used to open the text file in C
writing as well as reading mode?
a)f=open(“c:\data.txt”,‟r‟) b)f=open(“c:\data.txt”,‟w+‟)
c)f=open(c:\\data.txt”,‟w+) d) f=open(“c:\\data.txt”,‟w‟)
15. hich of the following statements is true regarding the opening modes of a A
file?
a) While opening a file for reading, if the file does not exist, an error
occurs.
b) While opening a file for writing ,if the file does not exist, an error
occurs.
c) While opening a file for reading, if the file does not exist, a new file is
created.
d) None of the above.
16. State True or False True
“csv files are special text files”
17. State True or False True
“text files are slower in processing as they requires translation of special
characters”
18. Assertion(A): File opened in‟ w‟ mode always places the cursor at the A
beginning of the file and never generates an error.
Reason(R): „w‟ mode creates the file even if the file doesn‟t exist.
a) Both A and R are true and R is the correct explanation of A.
b) Both A and R are true but R is not the correct explanation of A.
c) A is true but R is false.
d) R is true but A is false.
19. Assertion(A):Text file contains data in human readable form. C
Reason(R): It executes faster than any other type of the file.
a) Both A and R are true and R is the correct explanation of A.
b) Both A and R are true but R is not the correct explanation of A.
c) A is true but R is false.
d) R is true but A is false.
20. Assertion(A): read()and readline() are used to read the data from the text B
file.
Reasoning(R): readlines() function is used to read all lines from the file
in the form of a List.
a) Both A and R are true and R is the correct explanation of A.
b) Both A and R are true but R is not the correct explanation of A.
c) A is true but R is false.
d) R is true but A is false.
2 Mark questions
1. What is the difference between read() and readline() function of text files?
Ans The read() function read specified number of n bytes. If n is not specified, read the entire
file.
e.g. s=f.read(10) #read 10 bytes
s= f.read() # read the entire file
The readline() function read a single line. If n is specified , read n bytes from the file.
e.g. p=f.readline() # read single line
p=f.readline(7) # read 7 bytes from the file
2. What is the difference between readlines() and readline() function used with the text file?
Ans The function readlines() read all the lines of the text file and store them as elements of the
List.
e.g. s= f.readlines() # all lines of text file will be read and store in list s
The function readline() will read a single line from the text file and if n is specified as the
argument, read n bytes from the file.
e.g. p=f.readline() # read single line
p=f.readline(7) # read 7 bytes from the file
3. Name the functions used to write data on the text files. Explain
Ans The two functions write() and writelines() are used to write data on the text files.
a)write()- This function writes a group of characters on to the text file.
e.g. s=”Computer Science”
f.write(s) # It will write string s to the file using file object f
b) writelines()- This function write strings in List as Lines to the file.
e.g. f.writelines(L) # It will write strings in List L as lines in the file using file pointer f.
4. What is the difference between „w‟ and „a‟ mode used while opening a text file?
Ans When „w‟ mode is used while opening the text file , it opens the file in write mode and
places the cursor at the beginning of the file and truncates the data of the file. And if file
doesn‟t exist ,it creates the file.
Whereas when „a‟ mode is used while opening the file, it opens the file in append mode and
places the cursor at the end of the file for adding the data at the end. Here also file is created
, if file doesn‟t exist.
5. What is the difference between „r+‟ mode and „w+‟ mode used while opening the text file?
Ans With both the modes reading and writing operations can take place, but difference is that if
file is opened using „w+‟ mode, file is created if file doesn‟t exist, whereas if file is opened
using „r+‟ mode, error is raised if file doesn‟t exist.
6. If the focus.txt file contains the following text:
Mindfulness, cognitive training, and a healthy lifestyle may help sharpen your focus.
Find the output of the following code:
F=open(“focus.txt”,‟r‟)
S=F.read(11)
print(S)
F.close()
Mindfulness
Ans
7. Find the output of the following code:
F=open(“focus.txt”,‟r‟)
S= F.readline()
print(S)
T=F.readline()
print(T)
F.close()
Ans Mindfulness, cognitive training, and a healthy lifestyle may help
sharpen your focus
8. Find the output of the following code:
F=open(“focus.txt”,‟r‟)
L= F.readlines()
for a in L:
print(a.upper())
F.close()
Ans MINDFULNESS, COGNITIVE TRAINING, AND A HEALTHY LIFESTYLE MAY HELP
SHARPEN YOUR FOCUS
9. Find the output of the following code:
F=open(“focus.txt”,‟a+‟)
S= “ sleep reduces stress hormones that can be harmful to the brain”
F.write(S)
F.seek(0) # bring cursor to the beginning of the file
L=F.readlines()
print(L)
F.close()
Ans ['Mindfulness, cognitive training, and a healthy lifestyle may help\n', 'sharpen your focus
sleep reduces stress hormones that can be harmful to the brain']
10. Find the output of the following code:
F=open(“wish.txt”, ‟w‟)
F.write(“Day”)
F.close()
If the file contains “Good” before execution, what will be the contents of the file after
execution of the above code.
Ans After execution, file will contain “Day” only as previous data will be truncated by write
operation over the file.
3 Marks questions
1. Write a program to read text file story.txt and count number of lines starting with
letter „A‟ or „a‟.
Ans F=open("story.txt",'r')
count=0
L=F.readlines()
for i in L:
if i[0]=='A' or i[0]=='a':
count=count+1
print("no. of lines starting with a=",count)
F.close()
2. Write a program to read the file data.txt and count number of uppercase, lowercase
in it.
Ans F=open("data.txt",'r')
u=0
l=0
s=F.read()
for i in s:
if i.isupper():
u=u+1
if i.islower():
l=l+1
print("Number of uppercase characters=",u)
print("Number of lowercase characters=",l)
F.close()
3. Write a program to read the file data.txt and count number of spaces in it.
Ans F=open("data.txt",'r')
space=0
s=F.read()
for i in s:
if i.isspace():
space=space+1
print("Number of spaces=",space)
F.close()
4. Write a program to read the file hash.txt and display the number characters up to
first #.
Ans F=open("hash.txt",'r')
count=0
s=F.read()
for i in s:
if i!='#':
count=count+1
else:
break
print("Number of characters up till # =",count)
F.close()
5. Write a program to read the file alphabet.txt and display all the lines in uppercase.
Ans F=open("alphabet.txt",'r')
L=F.readlines()
for i in L:
print(i.upper())
F.close()
6. Write a program to read the file data.txt and count number of lines present in it.
Ans F=open("data.txt",'r')
L=F.readlines()
print("Number of lines in the file=",len(L))
F.close()
7. Write a program to read the file data.txt and display only the digits present in it.
Ans F=open("data.txt",'r')
s=F.read()
for letter in s:
if letter.isdigit():
print(letter)
F.close()
8. Write a program to read the file story.txt and display second last line of the file.
Ans F=open("story.txt",'r')
L=F.readlines()
print(L[-2])
F.close()
9. Write a program to read the file article.txt and count occurrences of words “the” in
the file.
Ans F=open("article.txt",'r')
count=0
s=F.read()
L=s.split()
for word in L:
if word=="the":
count=count+1
print("No. of occurences of word the=",count)
F.close()
10. Write a program to read the file letter.txt and display those words which has less
than or equal to four characters.
Ans F=open("story.txt",'r')
s=F.read()
L=s.split()
for word in L:
if len(word)<=4:
print(word)
F.close()
4 Marks questions
1 Write python statements for opening the following files. Also, write the Python
statements to open the following files:
a) a text file “example.txt” in both read and write mode
b) a text file “bfile.dat” in write mode
c) a text file “try.txt” in append and read mode
d) a text file “btry.dat” in read only mode.
Ans (a) F = open(„example.txt‟,”r+”)
(b) F = open(“bfile.dat” , “w”)
(c) F = open(„try.txt‟ , “a”)
(d) F = open(„btry‟ , ‟r‟)
2 (i) What is the difference between the following set of statements (a) and (b):
a) P = open(“practice.txt”,”r”)
P.read(10)
b) with open(“practice.txt”, “r”) as P:
x = P.read()
Set of statements (a) would read the file “practice.txt” and returns a string that
Ans contains first 10 characters of the text file.
Set of statements (b) will read the text file “practice.txt” and returns a string that
contains entire contents of the text file.
(ii) Write a command(s) to write the following lines to the text file named hello.txt.
Assume that the file is opened in append mode.
“ Welcome my class”
“It is a fun place”
“You will learn and play”
Ans F = open(“TFILE.txt”, „a‟)
L = [“ Welcome my class” , “It is a fun place” , “You will learn and play”]
F.writelines(L)
F.close()
3 Write a method/function COUNTLINES_ET() in python to read lines from a text
file REPORT.TXT, and COUNT those lines which are starting either with „E‟ and
starting with „T‟ respectively. Display the Total count separately.
Ans def COUNTLINES_ET():
f=open(“REPORT.TXT”)
d=f.readlines()
le=0
lt=0
for i in d:
if i[0]==‟E:
le=le+1
elif i[0]==‟T‟:
lt=lt+1
print(“no of line start with”,le)
print(“no of line start with”,lt)
4 Write a function filter(oldfile, newfile) that copies all the lines of a text file
“source.txt” onto “target.txt” except those lines which starts with “@” sign.
Ans def filter(oldfile, newfile):
f1 = open("oldfile","r")
f2 = open(“newfile”,”w”)
while True:
text= f1.readline()
if len(text) ==0:
break
if text[0] == „@‟:
continue
f2.write(text)
f1.close()
f2.close()
5 (i) Write a user defined function countwords() to display the total number of words
present in the file from a text file “Quotes.Txt”.
Ans def countwords():
s = open("Quotes.txt","r")
f = s.read()
z = f.split ()
print ("Total number of words:", len(z))
(ii) Write a function COUNT_AND( ) in Python to read the text file “STORY.TXT”
and count the number of times “AND” occurs in the file. (include AND/and/And in
the counting)
Ans def COUNT_AND( ):
count=0
file=open(„STORY.TXT','r')
line = file.read()
word = line.split()
for w in word:
if w.upper() ==‟AND‟:
count=count+1
print(count)
file.close()
5 Marks questions
1 (i) Differentiate between Text files and Binary files.
Ans Text file: A text file is simply a sequence of ASCII or Unicode characters.A line is a
sequence of characters, stored on permanent storage. In a text file, each line is
terminated by a special character, known as End Of Line (EOL). Text file can be
created using any text editor. Ex. Myfile.txt.
Binary file: 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.
(ii) Write a method COUNTWORDS() in Python to read data from text file
„ARTICLE.TXT‟ and display the count of words which ends with a vowel.
For example, if the file content is as follows:
An apple a day keeps you healthy and wise
The COUNTWORDS() function should display the output as:
Total words which ends with vowel = 4
Ans def COUNTWORDS():
fil = open('ARTICLE.TXT' , 'r')
data = fil.read()
words = data.split()
count = 0
for w in words:
if w[-1] in 'aeiouAEIOU':
count += 1
fil.close()
print('Total words which ends with vowel =',count)
2 (i) Explain seek() and tell() methods.
Ans seek() method is used to position the file object at a particular position in a file.
The syntax of seek() is:
file_object.seek(offset [, reference_point])
For example, the statement fileObject.seek(5,0) will position the file object at 5th
byte position from the beginning of the file.
tell() method returns the current file position. This function returns an integer that
specifies the current position of the file object in the file. The position so specified
is the byte position from the beginning of the file till the current position of the file
object. The syntax of using tell() is:
file_object.tell()
(ii) Write a function COUNT() in Python to read from a text file „rhym.txt' and display
the count of words in each line.
Example: If the content of „rhym.txt‟ is as follows:
Jack and jill
Went up the hill
To enjoy
Then the COUNT() function should display output as:
Line 1 : 3
Line 2 : 4
Line 3 : 2
Ans def COUNT():
fil = open('rhym.txt')
lines = fil.readlines()
c=1
for l in lines:
words = l.split()
print('Line',c,':',len(words))
c = c+1
fil.close()
3 (i) Differentiate between w+ and a+ file modes.
Ans
Parameter w+ Mode a+ Mode
Opens a file for reading
Opens a file for reading and
Description and appending (creates
writing (truncate file).
file if not exists).
Points at the beginning of the Points at the end of the
File Pointer file after opening. file after opening.
Overwrites existing content Appends new data to the
Write Operation with new data. end of the file.
Reads from the beginning of the Reads from the beginning
Read Operation file. of the file.
Truncates the file to zero length Does not truncate the file;
File Truncation
if it exists. preserves existing content.
Creates a new file if it does notCreates a new file if it
Creation exist. does not exist.
Useful for scenarios
Useful for scenarios where
where data needs to be
existing content needs to be
Usage appended to an existing
overwritten or a new file needs
file without losing the
to be created.
existing content.
(ii) Write a function WE_WORDS() in Python to read from a text file „TEXT.TXT‟ and
display the count of words which starts with „WE‟.
Example: If the content of „TEXT.TXT‟ is as follows:
WE MUST WELCOME ALL WEATHER FROM WEST
Then the WE_WORDS() function should display output as:
TOTAL WORDS STARTING WITH WE = 4
Ans def WE_COUNT():
fil = open('TEXT.TXT')
data = fil.read()
words = data.split()
count = 0
for w in words:
if w.startswith('WE'):
count = count + 1
print('TOTAL WORDS STARTING WITH WE=',count)
fil.close()
4 (i) What will be the return datatype of the following methods:
read()
readlines()
Ans read() – String
readlines() – List
(ii) A pre-existing text file data.txt has some words written in it. Write a python
function displaywords() that will print all the words that are having length greater
than 3.
Example:
For the fie content:
A man always wants to strive higher in his life He wants to be perfect.
The output after executing displayword() will be: Always wants strive higher life
wants perfect
Ans def displaywords():
f = open('data.txt','r')
s = f.read()
lst = s.split() for x in lst:
if len(x)>3:
print(x, end=" ")
f.close()
5 (i) Explain the use of seek() method.
Ans seek() method is used to position the file object at a particular position in a file.
The syntax of seek() is:
file_object.seek(offset [, reference_point])
In the above syntax, offset is the number of bytes by which the file object is to be
moved. reference_point indicates the starting position of the file object. That is,