Question:

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.
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Below is a Python function that does this:

def display_vote_lines():
    with open("Elections.txt", "r") as f:
        for line in f:
            if "vote" in line:
                print(line.strip())
This function opens the file "Elections.txt" in read mode.
It uses with open() to handle the file safely,
so that it closes automatically after reading.
The function reads each line one by one inside a for loop.
If the line contains the word "vote",
it prints the line using print() after stripping extra spaces.
This ensures that only lines with the word "vote" are displayed.
Was this answer helpful?
0
0