VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-obtain-the-line-number-in-which-given-word-is-present-using-python/

โ‡ฑ How to Obtain the Line Number in which Given Word is Present using Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Obtain the Line Number in which Given Word is Present using Python

Last Updated : 17 Nov, 2025

Given a text file, find the line number where a specific word or phrase appears. Below is the Input File used in this article:

๐Ÿ‘ file1
File1.txt

Below are the methods to find the line number:

Using next() with a Generator Expression

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(f, start=1): iterates lines with line numbers.
  • next((n for ... if word in line), None): finds the first line number containing the word, returns None if not found.
  • Conditional print: displays line number if found, else shows not found.

Using enumerate()

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:

  • enumerate(f, start=1): automatically tracks line numbers.
  • if word in line: checks for the target word.

Using a Manual Counter

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:

  • n += 1: manually counts lines.
  • if word in line: checks each line for the word.

Using readlines() + enumerate()

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:

  • f.readlines(): reads all lines into a list.
  • enumerate(lines, start=1): iterates with line numbers starting at
  • if word in line: checks each line for the word.

Related Articles:

Comment