Test Index
File Handling in Python
© examsnet.com
Question : 35 of 37
Marks:
+1,
-0
(a) Write a function in Python that displays the book names having ‘Y’ or ‘y’ in their name from a text file “Bookname.txt”.Example :If the file ‘Bookname.txt’ contains the names of following books :One Hundred Years of SolitudeThe Diary of a Young GirlOn the RoadAfter execution, the output will be :One Hundred Years of SolitudeThe Diary of a Young GirlOR(b) Write a function
RevString() to read a textfile “Input.txt” and prints the words starting with ‘O’ in reverse order. The rest of the content is displayed normally.Example :If content in the text file is :UBUNTU IS AN OPEN SOURCE OPERATING SYSTEMOutput will be :UBUNTU IS AN NEPO SOURCE GNITAREPO SYSTEM(words ‘OPEN’ and ‘OPERATING’ are displayed in reverse order)[CBSE 2023 Compartment]
Solution:
(a)
def Book_Name(): fin = open("Bookname.txt", "r") lines = fin.readlines() for line in lines: if 'Y' in line or 'y' in line: print(line, end="") fin.close()Book_Name()Explanation: The file is opened in read mode and readlines() gives a list of all book names. Each line is checked one by one with the in operator; a name containing 'Y' or 'y' is displayed (end="" because each line already ends with a newline). For the sample file, "One Hundred Years of Solitude" and "The Diary of a Young Girl" are displayed; "On the Road" has no y.OR (b)def RevString(): fin = open("Input.txt", "r") S = fin.read() for w in S.split(): if w[0] == 'O': print(w[::-1], end=' ') else: print(w, end=' ') fin.close()RevString()Explanation: read() reads the whole text and split() separates it into words. For each word the first character w[0] is checked; a word starting with 'O' is printed reversed using the slice w[::-1], every other word is printed as it is. For the sample, OPEN becomes NEPO and OPERATING becomes GNITAREPO.© examsnet.com
Go to Question: