Test Index

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

© examsnet.com
Question : 24 of 37
Marks: +1, -0
(a) Write a method/function COUNTWORDS() in Python to read contents from a text file DECODE.TXT, to count and return the occurrence of those words, which are having 5 or more characters.
OR
(b) Write a method/function COUNTLINES() in Python to read lines from a text file CONTENT.TXT, and display those lines, which have @ anywhere in the line.
For example :
If the content of the file is :
Had an amazing time at the concert last night with @MusicLoversCrew.
Excited to announce the launch of our new website!
G20 @ India
The method/function should display
Had an amazing time at the concert last night with @MusicLoversCrew
G20 @ India
[CBSE 2024 Compartment]
Solution:  
(a)
def COUNTWORDS():
count = 0
with open("DECODE.TXT", "r") as f:
words = f.read().split()
for w in words:
if len(w) >= 5:
count += 1
return count
Explanation: The file is opened in read mode, the whole text is read and split() breaks it into words at spaces and newlines. Each word with 5 or more characters is counted, and the count is returned.
OR (b)
def COUNTLINES():
f = open("CONTENT.TXT", "r")
lines = f.readlines()
for line in lines:
if "@" in line:
print(line.rstrip("\n"))
f.close()
Explanation: readlines() returns a list of all lines. The in operator checks whether '@' occurs anywhere in a line; such lines are displayed (rstrip("\n") removes the newline so no blank line is printed between them). For the sample file, the first and third lines are displayed.
© examsnet.com
Advertisements
Go to Question: