Test Index
CBSE Class 12 Computer Science 2026 Paper Compartment
© examsnet.com
Question : 29 of 37
Marks:
+1,
-0
(a) Write a user-defined function in Python named Find_Pattern() which reads the contents of a text file named LOGS.TXT and displays all such lines that begin with the word "ERROR" (case-sensitive).For example, if the content of file LOGS.TXT is as follows :
INFO: System startup complete.WARNING: Disk space low on drive C:.ERROR: Failed to connect to database.INFO: User 'admin' logged in.DEBUG: Processing request 'GET /data'.ERROR: Invalid input received from client.SUCCESS: Data saved.Then the function should display the lines :
ERROR: Failed to connect to database.ERROR: Invalid input received from client.OR(b) Write a user-defined function in Python named ContainsChar() which reads the contents of a text file named DOCUMENT.TXT and displays all such words that contain the letter 'o' (case-insensitive).For example, if the content of file DOCUMENT.TXT is as follows :
"A brown fox quickly jumped over the dog. It loves to frolic."Then the function should display the following words:
brownfoxoverdog.lovestofrolic.
Solution:
(a)Concept: Open the file in read mode and go through it line by line. The string method
startswith("ERROR") is case-sensitive, so only lines whose first characters are exactly ERROR are printed.def Find_Pattern(): with open("LOGS.TXT", "r") as F: for line in F: if line.startswith("ERROR"): print(line, end="")Explanation:1. with open("LOGS.TXT", "r") as F opens the file for reading and closes it automatically.2. for line in F reads one line at a time (each line ends with \n).3. line.startswith("ERROR") is True only for the 3rd and 6th lines of the sample file; end="" stops a blank line being printed after each line, since the line already has its own newline.Output for the sample file:ERROR: Failed to connect to database.ERROR: Invalid input received from client.Key point:
line[0:5] == "ERROR" works equally well. Do not use line.upper(), because the check must be case-sensitive.OR (b)Concept: Read the whole file, split it into words with split() (splits on spaces and newlines), and print each word that contains 'o'. Converting the word to lower case first makes the test case-insensitive (it also catches 'O').def ContainsChar(): with open("DOCUMENT.TXT", "r") as F: data = F.read() words = data.split() for w in words: if 'o' in w.lower(): print(w)Explanation:For the sample text the words are A, brown, fox, quickly, jumped, over, the, dog., It, loves, to, frolic. Only brown, fox, over, dog., loves, to and frolic. contain an o, so the output is:brownfoxoverdog.lovestofrolic.Key point:
split() keeps punctuation attached to a word, which is why dog. and frolic. are printed with the full stop, exactly as the example shows.© examsnet.com
Go to Question: