Test Index

File Handling in Python Get it on Google PlayDownload on the App Store CBSE Board Videos

© examsnet.com
Question : 29 of 37
Marks: +1, -0
(a) Write the definition of a Python function named LongLines( ) which reads the contents of a text file named 'LINES.TXT' and displays those lines from the file which have at least 10 words in it. For example, if the content of 'LINES.TXT' is as follows :
Once upon a time, there was a woodcutter
He lived in a little house in a beautiful, green wood.
One day, he was merrily chopping some wood.
He saw a little girl skipping through the woods, whistling happily.
The girl was followed by a big gray wolf.
Then the function should display output as :
He lived in a little house in a beautiful, green wood.
He saw a little girl skipping through the woods, whistling happily.
OR
(b) Write a function count_Dwords() in Python to count the words ending with a digit in a text file "Details.txt".
Example:
If the file content is as follows :
On seat2 VIP1 will sit and
On seat1 VVIP2 will be sitting
Output will be:
Number of words ending with a digit are 4
[CBSE 2023 Set 4]
Solution:  
(a)
def LongLines():
myfile = open('LINES.TXT', 'r')
all_lines = myfile.readlines()
for aline in all_lines:
if len(aline.split()) >= 10:
print(aline, end='')
myfile.close()
LongLines()
Explanation: readlines() gives a list of the lines; split() breaks a line into words at white space, so len(aline.split()) is the number of words. In the example the lines have 8, 11, 8, 11 and 9 words, so only the 2nd and 4th lines are displayed.
OR (b)
def count_Dwords():
F = open("Details.txt", "r")
words = F.read().split()
count = 0
for W in words:
if W[-1].isdigit():
count += 1
print("Number of words ending with a digit are", count)
F.close()
count_Dwords()
Explanation: W[-1] is the last character of a word and isdigit() checks whether it is a digit. In the example: seat2, VIP1, seat1, VVIP2, so the count is 4.
© examsnet.com
Advertisements
Go to Question: