Write a function in Python to read a text file, Beta.txt and displays those lines which end with the word ‘done’.
Answer:
Answer by student
Detailed answer by teachoo
-lock-
- The code defines a function named display_done_lines that takes one parameter filename, which is the name of the text file to be read.
- The function performs the following steps:
- It opens the file in read mode using the open function and assigns the file object to a variable called file . This allows the function to access the contents of the file.
- It loops through each line in the file using a for loop . In each iteration, it assigns the current line to a variable called line.
- It checks if the line ends with the word ‘done’ followed by a newline character (\n) using the endswith method. This method returns True if the string ends with the specified suffix, and False otherwise. The suffix ‘done\n’ is passed as an argument to the method.
- If the condition is True, it prints the line without the newline character using the print function and slicing . Slicing is a way of accessing a part of a string using its index. The syntax is string[start:end:step], where start is the starting index, end is the ending index (exclusive), and step is the increment. If any of these are omitted, they are assumed to be default values. The default value of start is 0, end is the length of the string, and step is 1. The expression line[:-1] means to slice from the beginning of the line to one character before the end of the line, which effectively removes the last character (\n). This displays the line on the screen without an extra newline.
- After the loop ends, it closes the file using the close method. This releases any resources used by the file object and prevents any errors or data loss.
The final code is as follows:
-endlock-