Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Find Line Number of a Given Word in text file using Python?
In this article, we will show you how to find the line number where a specific word appears in a text file using Python. This is useful for searching keywords in documents, logs, or code files.
Let's assume we have a text file named TextFile.txt with the following content ?
Good Morning TutorialsPoint This is TutorialsPoint sample File Consisting of Specific source codes in Python,Seaborn,Scala Summary and Explanation Welcome TutorialsPoint Learn with a joy
Algorithm
Following are the steps to find line numbers containing a specific word ?
Open the text file in read mode
Initialize a line counter starting from 1
Iterate through each line of the file
Split each line into words and check if the target word exists
Print the line number when the word is found
Increment the line counter for each line processed
Method 1: Using split() and in Operator
This method splits each line into words and checks for exact word matches ?
# Create a sample text file first
with open("TextFile.txt", "w") as f:
f.write("Good Morning TutorialsPoint\n")
f.write("This is TutorialsPoint sample File\n")
f.write("Consisting of Specific\n")
f.write("source codes in Python,Seaborn,Scala\n")
f.write("Summary and Explanation\n")
f.write("Welcome TutorialsPoint\n")
f.write("Learn with a joy\n")
# Find line numbers containing the word
target_word = "TutorialsPoint"
line_number = 1
print(f"The word '{target_word}' is present in the following lines:")
with open("TextFile.txt", "r") as file:
for line in file:
# Split the line into words
words = line.split()
# Check if target word exists in the words list
if target_word in words:
print(line_number)
line_number += 1
The word 'TutorialsPoint' is present in the following lines: 1 2 6
Method 2: Using enumerate() for Cleaner Code
The enumerate() function automatically handles line numbering ?
target_word = "TutorialsPoint"
found_lines = []
with open("TextFile.txt", "r") as file:
for line_num, line in enumerate(file, 1):
if target_word in line.split():
found_lines.append(line_num)
print(f"Word '{target_word}' found on lines: {found_lines}")
Word 'TutorialsPoint' found on lines: [1, 2, 6]
Method 3: Case-Insensitive Search
To make the search case-insensitive, convert both the line and target word to lowercase ?
target_word = "tutorialspoint" # lowercase search term
with open("TextFile.txt", "r") as file:
for line_num, line in enumerate(file, 1):
# Convert to lowercase for case-insensitive comparison
words = [word.lower() for word in line.split()]
if target_word.lower() in words:
print(f"Line {line_num}: {line.strip()}")
Line 1: Good Morning TutorialsPoint Line 2: This is TutorialsPoint sample File Line 6: Welcome TutorialsPoint
Method 4: Using a Function
Create a reusable function to find word occurrences ?
def find_word_lines(filename, word, case_sensitive=True):
"""
Find line numbers containing a specific word.
Args:
filename: Path to the text file
word: Word to search for
case_sensitive: Whether to perform case-sensitive search
Returns:
List of line numbers where word is found
"""
found_lines = []
try:
with open(filename, "r") as file:
for line_num, line in enumerate(file, 1):
words = line.split()
if case_sensitive:
if word in words:
found_lines.append(line_num)
else:
words_lower = [w.lower() for w in words]
if word.lower() in words_lower:
found_lines.append(line_num)
except FileNotFoundError:
print(f"File '{filename}' not found!")
return []
return found_lines
# Test the function
result = find_word_lines("TextFile.txt", "TutorialsPoint")
print(f"Word found on lines: {result}")
# Case-insensitive search
result_case_insensitive = find_word_lines("TextFile.txt", "python", False)
print(f"Word 'python' found on lines: {result_case_insensitive}")
Word found on lines: [1, 2, 6] Word 'python' found on lines: [4]
Comparison
| Method | Advantages | Best For |
|---|---|---|
| Basic split() method | Simple and straightforward | One-time searches |
| enumerate() | Cleaner code, automatic numbering | Better readability |
| Case-insensitive | More flexible searching | User input searches |
| Function approach | Reusable, error handling | Production code |
Conclusion
Use the split() method with the in operator for exact word matching. For more flexible applications, implement case-insensitive search and wrap the logic in a reusable function with proper error handling.
