Question:medium

Write a Python function that displays all the lines containing the word 'vote' from a text file "Elections.txt".
For example, if the file contains:
In an election many people vote to choose their representative.
The candidate getting the maximum share of votes stands elected.
Normally, one person has to vote once.
The process of voting may vary with time and region.
Then the output should be:
In an election many people vote to choose their representative.
Normally, one person has to vote once.

Show Hint

Always use with open() for file operations.
It automatically closes the file after use, avoiding resource leaks.
Updated On: Jan 14, 2026
Show Solution

Solution and Explanation

The following Python function accomplishes this task:
def display_vote_lines():
    with open("Elections.txt", "r") as f:
        for line in f:
            if "vote" in line:
                print(line.strip())
This function accesses the file "Elections.txt" for reading. It employs with open() for secure file handling, ensuring automatic closure post-read. The function iterates through each line sequentially within a for loop. If a line contains the substring "vote", it is printed using print() after removing leading/trailing whitespace. Consequently, only lines containing the word "vote" are outputted.
Was this answer helpful?
0