![]() |
VOOZH | about |
Given a text file, find the line number where a specific word or phrase appears. Below is the Input File used in this article:
Below are the methods to find the line number:
This method uses a generator expression with next() to efficiently find the first line containing the target word. It automatically stops searching once the word is found, making it concise and fast.
Output
The word writer is found in line number: 2
Explanation:
enumerate() lets you loop through the file lines while automatically keeping track of line numbers.
Output
The word writer is found in line number: 2
Explanation:
You can find a wordโs line number by reading the file line by line and keeping a simple counter to track the current line.
Output
The word writer is found in line number: 2
Explanation:
This method reads all lines into memory first. Suitable for small files, but not recommended for very large files.
Output
The word writer is found in line number: 2
Explanation: