How to Obtain the Line Number in which Given Word is Present using Python (original) (raw)

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.

Python `

word = "writer"

with open("file1.txt", 'r') as f: res = next((n for n, line in enumerate(f, start=1) if word in line), None)

if res: print("The word", word, "is found in line number:", res) else: print("The word", word, "is not found in the file.")

`

**Output

The word writer is found in line number: 2

**Explanation:

Using enumerate()

enumerate() lets you loop through the file lines while automatically keeping track of line numbers.

Python `

word = "writer"

with open("file1.txt", 'r') as f: for n, line in enumerate(f, start=1): if word in line: print("The word", word, "is found in line number:", n) break else: print("The word", word "is not found in the file.")

`

**Output

The word writer is found in line number: 2

**Explanation:

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.

Python `

word = "writer" n = 0

with open("file1.txt", 'r') as f: for line in f: n += 1 if word in line: print("The word", word, "is found in line number:", n) break else: print("The word", word, "is not found in the file.")

`

**Output

The word writer is found in line number: 2

**Explanation:

Using readlines() + enumerate()

This method reads all lines into memory first. Suitable for small files, but not recommended for very large files.

Python `

word = "writer"

with open("file1.txt", 'r') as f: lines = f.readlines()

for i, line in enumerate(lines, start=1): if word in line: print("The word", word, "is found in line number:", i) break else: print("The word", word, "is not found in the file.")

`