Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Pulling a random word or string from a line in a text file in Python
Next article icon

Find line number of a specific string or substring or word from a .txt file in Python

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Finding the line number of a specific string and its substring is a common operation performed by text editors or any application with some level of text processing capabilities. 

In this article, you will learn how to find line number of a specific string or substring or word from a .txt (plain text) file using Python. 

The problem in hand could be stretched to include different methods. i.e. The line number of the first occurrence of the substring/string could be found, or the line numbers at which the string/substring exists could be found. This article will be going over the latter one.

For demonstration the following text file would be used:

 

 Finding single word in a text file

In this part, we will search for a single word in the text file. Let’s see the code here.

Python3

# Name of the file in which the string is to be searched
filename = r"test1.txt"
 
# The string that is to be searched
key = "the"
 
# Opening the file and storing its data into the variable lines
with open(filename) as file:
    lines = file.readlines()
 
# Going over each line of the file
for number, line in enumerate(lines, 1): 
     
    # Condition true if the key exists in the line
    # If true then display the line number
    if key in line: 
        print(f'{key} is at line {number}') 
                      
                       

Output:

"the" is at line 2 "the" is at line 5 "the" is at line 7

Explanation:

Firstly the variables filename and key were initialized. The variable filename stores the path (absolute or relative) of the text file. The variable key stores the string that is to be searched. Afterward, the file at the path specified by the filename variable is opened for the read operation. All the lines within the files are read and stored in the variable lines. A for-loop is ran where this variable is passed through the enumerate function to get each line along with its number as the condition. Therefore, the loop would execute until all the elements of the lines list are exhausted. Then a condition is placed inside the loop, which searches for the key within the line using the in operator. If the presence is found, the line at which the key is found is printed, and this process repeats until all the lines within the file are checked. 

Finding different words in a text file

In this part, we will search for a different words in the text file. Let’s see the code here.

Python3

# Name of the file in which the string is to be searched
filename = r"test1.txt"
 
# The list containing the strings that are to be searched
key = ["the", "and", "or", "to"]
 
# Opening the file and storing its data into the variable lines
with open(filename) as file:
    lines = file.readlines()
 
# Going over each element of the list
for x in key:
 
    # Same as the one for finding only one key
    for number, line in enumerate(lines, 1):     
        if x in line: 
            print(f'{x} is at line {number}') 
                      
                       

Output:

the is at line 2 the is at line 5 the is at line 7 and is at line 3 and is at line 4 and is at line 5 and is at line 6 or is at line 2 or is at line 3 or is at line 4 or is at line 5 or is at line 6 or is at line 7 to is at line 2 to is at line 3 to is at line 5

Explanation:

The working logic of the code is safe as the aforementioned one. The only difference being that we are supplying more than 1 key to be searched into the file in a loop. Therefore, in this way we can find many different substrings within the file, at the same time.

Finding different substrings in a text file

In this part, we will search for  substring in the text file. Let’s see the code here.

Python3

def search(key, file):
    # Opening the file and storing its data into the variable lines
    with open(filename) as file:
        lines = file.readlines()
    for number, line in enumerate(lines, 1):
        # Going over each key
        if key in line:
            print(f'{key} is at line {number}')
 
 
# Name of the file in which the string is to be searched
filename = r"test1.txt"
key = "in hand"
string_list = list(key.split())
for item in string_list:
    search(item, filename)
                      
                       

Output:

in is at line 1 in is at line 3 hand is at line 3


Next Article
Pulling a random word or string from a line in a text file in Python

V

vasudev4
Improve
Article Tags :
  • Python
  • Technical Scripter
  • Technical Scripter 2022
Practice Tags :
  • python

Similar Reads

  • Pulling a random word or string from a line in a text file in Python
    File handling in Python is really simple and easy to implement. In order to pull a random word or string from a text file, we will first open the file in read mode and then use the methods in Python's random module to pick a random word.  There are various ways to perform this operation: This is the
    2 min read
  • Read a text file into a string variable and strip newlines in Python
    It is quite a common requirement for users to remove certain characters from their text files while displaying. This is done to assure that only displayable characters are displayed or data should be displayed in a specific structure. This article will teach you how to read a text file into a string
    5 min read
  • Python - Replace all occurrences of a substring in a string
    Replacing all occurrences of a substring in a string means identifying every instance of a specific sequence of characters within a string and substituting it with another sequence of characters. Using replace()replace () method is the most straightforward and efficient way to replace all occurrence
    2 min read
  • How to obtain the line number in which given word is present using Python?
    To obtain the line number from the file where the given word is present, create a list in which each index contains the content of each line with Python. To do so follow the below instruction. Get Line Number of Certain Phrase in a Text fileBelow are the methods that we will cover in this article. U
    3 min read
  • Count number of lines in a text file in Python
    Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, If the file is small, you can use readlines() or a loop approach in Python. Input: line 1 line 2 line 3 Output:
    3 min read
  • Find the first repeated word in a string in Python using Dictionary
    We are given a string that may contain repeated words and the task is to find the first word that appears more than once. For example, in the string "Learn code learn fast", the word "learn" is the first repeated word. Let's understand different approaches to solve this problem using a dictionary. U
    3 min read
  • How to Find the Longest Line from a Text File in Python
    Finding the longest line from a text file consists of comparing the lengths of each line to determine which one is the longest. This can be done efficiently using various methods in Python. In this article, we will explore three different approaches to Finding the Longest Line from a Text File in Py
    3 min read
  • Find frequency of each word in a string in Python
    Write a python code to find the frequency of each word in a given string. Examples: Input : str[] = "Apple Mango Orange Mango Guava Guava Mango" Output : frequency of Apple is : 1 frequency of Mango is : 3 frequency of Orange is : 1 frequency of Guava is : 2 Input : str = "Train Bus Bus Train Taxi A
    7 min read
  • Shell Program to Find the Position of Substring in Given String
    A string is made of many substrings or can say that if we delete one or more characters from the beginning or end then the remaining string is called substring. This article is about to write a shell program that will tell the position (index) of the substring in a given string. Let's take an exampl
    7 min read
  • How to read specific lines from a File in Python?
    Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences