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:
How to Find all Files Containing Specific Text (string) on Linux
Next article icon

Python - How to search for a string in text files?

Last Updated : 14 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to see how to search for a string in text files using Python

Example:

string = "GEEK FOR GEEKS"
Input: "FOR" 
Output: Yes, FOR is present in the given string.

Text File for demonstration:

myfile.txt

Finding the index of the string in the text file using readline()

In this method, we are using the readline() function, and checking with the find() function, this method returns -1 if the value is not found and if found it returns 0.

Python3
# string to search in file with open(r'myfile.txt', 'r') as fp:     # read all lines using readline()     lines = fp.readlines()     for row in lines:         # check if string present on a current line         word = 'Line 3'         #print(row.find(word))         # find() method returns -1 if the value is not found,         # if found it returns index of the first occurrence of the substring         if row.find(word) != -1:             print('string exists in file')             print('line Number:', lines.index(row)) 

Output:

string exists in file line Number: 2

Finding string in a text file using read()

we are going to search string line by line if the string is found then we will print that string and line number using the read() function.

Python3
with open(r'myfile.txt', 'r') as file:         # read all content from a file using read()         content = file.read()         # check if string present or not         if 'Line 8' in content:             print('string exist')         else:             print('string does not exist') 

Output:

string does not exist

Search for a String in Text Files using enumerate()

We are just finding string is present in the file or not using the enumerate() in Python.

Python3
with open(r"myfile.txt", 'r') as f:     for index, line in enumerate(f):                  # search string         if 'Line 3y' in line:             print('string found in a file')                         # don't look for next lines             break              print('string does not exist in a file') 

Output:

string does not exist in a file

Next Article
How to Find all Files Containing Specific Text (string) on Linux

P

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

Similar Reads

  • How to search and replace text in a file in Python ?
    In this article, we will learn how we can replace text in a file using python. Method 1: Searching and replacing text without using any external module Let see how we can search and replace text in a text file. First, we create a text file in which we want to search and replace text. Let this file b
    5 min read
  • How to Read from a File in Python
    Reading from a file in Python means accessing and retrieving the contents of a file, whether it be text, binary data or a specific data format like CSV or JSON. Python provides built-in functions and methods for reading a file in python efficiently. Example File: geeks.txt Hello World Hello Geeksfor
    5 min read
  • How to search a pickle file in Python?
    Prerequisites: pickle file  Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to conver
    3 min read
  • How to read large text files in Python?
    In this article, we will try to understand how to read a large text file using the fastest way, with less memory usage using Python.  To read large text files in Python, we can use the file object as an iterator to iterate over the file and perform the required task. Since the iterator just iterates
    3 min read
  • How to Find all Files Containing Specific Text (string) on Linux
    Suppose you are looking for a file in Linux, but you have forgotten its name. You only remember the contents of the file. How will you find the file in this case? Well, there are some useful methods that will help you find a file containing a specific text (or string) in Linux. The string needs to b
    4 min read
  • How to remove brackets from text file in Python ?
    Sometimes it becomes tough to remove brackets from the text file which is unnecessary to us. Hence, python can do this for us. In python, we can remove brackets with the help of regular expressions.  Syntax: # import re module for using regular expression import re patn =  re.sub(pattern, repl, sent
    3 min read
  • Reading and Writing to text files in Python
    Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL
    8 min read
  • How to read multiple text files from folder in Python?
    Prerequisite: File Handlingos Python is a strong language which is extremely capable even when it comes to file handling. In this article, we will learn how to read multiple text files from a folder using python. Approach: Import modulesAdd path of the folderChange directoryGet the list of a file fr
    2 min read
  • Read File As String in Python
    Python provides several ways to read the contents of a file as a string, allowing developers to handle text data with ease. In this article, we will explore four different approaches to achieve this task. Each approach has its advantages and uses cases, so let's delve into them one by one. Read File
    3 min read
  • Search String in Text using Python-Tkinter
    Tkinter is the standard GUI library for Python. It provides a powerful object-oriented interface to the Tk GUI toolkit. In this article, we'll see how to search for a specific string in a given text window using Tkinter.NOTE : For more detailed information on Tkinter, refer to Python GUI - TtkinterM
    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