Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
How to obtain the line number in which given word is present using Python?
Next article icon

How to obtain the line number in which given word is present using Python?

Last Updated : 04 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 file

Below are the methods that we will cover in this article.

  • Using Iteration
  • Using Enumerate

Input file: File1.txt

Screenshot-2023-08-02-114506
File1.txt
Get line number in which the given word is present through Iteration

Here we can obtain the line number in which a given word is present in a file using Python by reading the file line by line and keeping track of the line number where the word is found and below is an example code for that. In which we iterate over every element using for loop and keep track by a variable line_number so that when we encounter the word we have the line_number of the line in which that word is present.

Python3
def find_word_line_number(filename, target_word):     line_number = 0      with open(filename, 'r') as file:         for line in file:             line_number += 1             if target_word in line:                 return line_number      # If the word is not found in the file, return None     return None  # Example usage filename = "File1.txt"  # Replace with the name of your file word_to_find = "hello"    # Replace with the word you want to find line_number = find_word_line_number(filename, word_to_find) if line_number is not None:     print(f"The word '{word_to_find}' is present in line number: {line_number}") else:     print(f"The word '{word_to_find}' is not found in the file.") 

Output: 

The word 'Romy' is present in line number: 1 

Time complexity: O(1)
Auxiliary space: O(n) where n is the size of the file as the entire file is being read and stored in the variable "read".

Obtain the line number in which the given word is present through Enumerate

Here we have another method to obtain the line in which a given word is present with the help of enumerate() a function in Python. With the help of this method, it allows us to iterate over lines of the file along with their line number directly, and when we find the word which matches the word in the input we print the word and line in which we find it.

Python3
def find_word_in_file(file_path, target_word):     try:         with open(file_path, 'r') as file:             for line_number, line in enumerate(file, start=1):                 if target_word in line:                     return line_number      except FileNotFoundError:         print("Error: The file was not found.")     except Exception as e:         print(f"An error occurred: {e}")      return None  # Return None if the word is not found in the file.   # Example usage: file_path = 'file1.txt' word_to_find = 'Abhishek' result = find_word_in_file(file_path, word_to_find) if result:     print(f"The word '{word_to_find}' was found in line number: {result}") else:     print(f"The word '{word_to_find}' was not found in the file.") 

Output:

The word 'Abhishek' was not found in the file.

Time complexity: O(1)
Auxiliary space: O(n) where n is the size of the file as the entire file is being read and stored in the variable "read".


Next Article
How to obtain the line number in which given word is present using Python?

R

romy421kumari
Improve
Article Tags :
  • Python
  • python-file-handling
  • Python file-handling-programs
Practice Tags :
  • python

Similar Reads

    Find line number of a specific string or substring or word from a .txt file in Python
    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 tex
    4 min read
    How to count the number of lines in a CSV file in Python?
    Counting the number of lines in a CSV file in Python means determining how many rows the file contains, including or excluding the header depending on your needs. For example, if your CSV file has 100 data rows plus one header row, the total line count is 101. We will use the following dataset to de
    2 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
    How to remove lines starting with any prefix using Python?
    Given a text file, read the content of that text file line by line and print only those lines which do not start with a defined prefix. Also, store those printed lines in another text file. There are the following ways in Python in which this task can be done Program to remove lines starting with an
    4 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